以下2行代码中的block1与block2的类型是不同的,block1是不定参数的block,而block2是无参数的block
void(^block1)(); void(^block2)(void);
下面的代码展示了一个参数不定的block的使用的例子:
#import "ViewController.h" typedef NS_ENUM(NSUInteger, DataType) { DataTypeWithoutMessage = 0, DataTypeWithMessage, }; @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self processDataForType:DataTypeWithoutMessage block:^void(NSUInteger code) { // code = 100 NSLog(@"code = %tu", code); }]; [self processDataForType:DataTypeWithoutMessage block:^void(NSUInteger code, NSString *message) { // code = 100, message = (null) NSLog(@"code = %tu, message = %@", code, message); }]; [self processDataForType:DataTypeWithMessage block:^void(NSUInteger code, NSString *message) { // code = 200, message = Hello World NSLog(@"code = %tu, message = %@", code, message); }]; } // 第二个参数block,其类型为void(^)(),圆括号中没有void,并不表示该block没有参数,而是表示该block为可变参数 - (void)processDataForType:(DataType)dataType block:(void(^)())block { switch (dataType) { case DataTypeWithoutMessage: !block ?: block(100); break; case DataTypeWithMessage: !block ?: block(200, @"Hello World"); break; default: break; } } @end
时间: 2024-11-18 22:20:31