標籤:
Block 的使用有兩種:1.獨立Block 。2.內聯Block 。
《一》獨立Block 使用方式
一、定義一個Block Object,並調用。
1.定義
// 定義一個Block Object,傳回值:NSString;別名:intToString;參數:NSUInteger。NSString* (^intToString)(NSUInteger) = ^(NSUInteger paramInteger){ NSString *result = [NSString stringWithFormat:@"%lu",(unsignedlong)paramInteger]; return result;};
2.調用
// 調用我們定義的Block OjbectNSString *string = intToString(10);NSLog(@"string = %@", string);
二、將Block Object 當作參數,在方法之間傳遞,調用。 有時候,我們希望將定義的Block Object作為函數的參數使用,就像其他的資料類型一樣。
1.為Block Object 定義簽名
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
這就告訴,編譯器,我們定義了一個簽名(別名)為IntToStringConverter 的Block Object。這個Block傳回值為:NSString;參數為:NSUInteger。
2.定義使用Block為參數的函數
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{ return paramBlockObject(paramInteger);}這一步,很簡單,我們將前面定義的Block作為了一種類型。這種類型為:IntToStringConverter
3.調用使用Block為參數的方法
NSString *result = [self convertIntToString:123 usingBlockObject:intToString]; NSLog(@"result = %@", result);
調用時,123,和intToString可理解為實參。
《二》內聯Block 使用方式 在此之前,讓我們梳理一下需要的代碼:
1.定義
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
2.用Block作為參數的函數
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{ return paramBlockObject(paramInteger);}
3.內聯調用
- (void) doTheConversion{ IntToStringConverter inlineConverter = ^(NSUInteger paramInteger){ NSString *result = [NSString stringWithFormat:@"%lu", (unsignedlong)paramInteger]; return result; }; NSString *result = [self convertIntToString:123usingBlockObject:inlineConverter]; NSLog(@"result = %@", result); }
iOS Block淺析