神刀安全网

在Objective-C中声明block

1.申明一个本地变量

returnType (^blockName)(parameterTypes) = ^returnType(parameters){...}
例如

bool (^isEventBlock)(NSInteger num) = ^bool(NSInteger num){     if (num % 2 == 0)         return YES;     else         return NO; };

2.申明一个属性

@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
例如

@property (nonatomic, copy,  nullability) bool (^evenBlock)(NSInteger num);

3.申明一个函数参数

-(void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes)) blockName;
例如

- (void)filterNumsWithEvenBlock:(bool (^)(NSInteger num)) evenBlock;  - (void)filterNumsWithEvenBlock:(bool (^)(NSInteger num)) evenBlock {     NSInteger num = 3;     evenBlock(3); }

4.作为一个函数调用的参数

[someObject someMethodThatTakesABlock:^returnType (parameters){...}];
例如

[self filterNumsWithEvenBlock:^bool (NSInteger num){     if (num % 2 == 0 )         return YES;     else         return NO; }];

5.重命名typedef

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters){...};
例如

typedef bool (^EvenBlock)(NSInteger num); EvenBlock evenBlock = ^bool (NSInteger num){     if (num % 2 == 0)         return YES;     else         return NO; };

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » 在Objective-C中声明block

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址