Block 是 Objective-C 中相當靈活的語言特性。本文將說明兩種常見的呼叫情境:由方法呼叫 Block Object,以及由一個 Block Object 呼叫另一個 Block Object。
#import <Foundation/Foundation.h> @interface TestDemo : NSObject - (void) callSimpleBlock; - (void) callTrimBlock; @end
#import "TestDemo.h"
@implementation TestDemo
/*************** 方法呼叫 Block Object Start ***************/
void (^simpleBlock)(NSString *) = ^(NSString *paramString){
// 在此實作區塊內容,並使用傳入的 paramString 參數
NSLog(@"%@", paramString);
};
- (void) callSimpleBlock{
simpleBlock(@"Archy");
}
/*************** 方法呼叫 Block Object End ***************/
/*************** Block Object 呼叫 Block Object Start ***************/
NSString *(^trimString)(NSString *) = ^(NSString *inputString){
NSString *result = [inputString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
return result;
};
NSString *(^trimWithOtherBlock)(NSString *) = ^(NSString *inputString){
return trimString(inputString);
};
- (void) callTrimBlock{
NSString *trimmedString = trimWithOtherBlock(@" Archy ");
NSLog(@"Trimmed string = %@", trimmedString);
}
/*************** Block Object 呼叫 Block Object End ***************/
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
TestDemo *test = [[TestDemo alloc] init];
// [test callSimpleBlock];
[test callTrimBlock];
}
return 0;
}
2013-05-10 06:53:50.893 CallBlockObjectTest[591:303] Trimmed string = Archy
可以看到 trimWithOtherBlock 內部呼叫了 trimString,成功把前後空白去除後輸出「Archy」。這說明了 Block 之間可以互相呼叫,形成類似巢狀函式的結構。