使用typedef的块
这是在块中使用typedef的简单示例。使用XCode运行相同的代码。在其他平台手动编译报错。
#import <Foundation/Foundation.h>
typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end
@implementation SampleClass
- (void)performActionWithCompletion:(CompletionBlock)completionBlock {
NSLog(@"Action Performed");
completionBlock();
}
@end
int main() {
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass performActionWithCompletion:^{
NSLog(@"Completion is called to intimate action is performed.");
}];
return 0;
}
让我们编译并执行它,它将产生以下结果-
2020-09-10 08:13:57.155 test[284:303] Action Performed
2020-09-10 08:13:57.157 test[284:303] Completion is called to intimate action is performed.
块更多地用于iOS应用程序和Mac OS X中。因此,了解块的用法更为重要。