iOS中Block声明方式

2020-03-12  本文已影响0人  小小在流浪

如何在Objective-C中声明一个Block?

接下来正文中出现词语定义:

returnType: 返回类型, NSInteger、BOOL、int、...
blockName: block名称,自己定义
parameterTypes: 参数类型 ,NSInteger、BOOL、int、...
parameters : 参数类型 +名 称 ,NSInteger index, BOOL flag ...
someObject : 对象,实例对象 、类对象、self、...

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

NSInteger (^myblock)(BOOL) = ^NSInteger(BOOL flag) {
  //code
  if(flag) return 1
  return 0;
};

@property (nonatomic, copy) returnType (^blockName)(parameters);

@property (nonatomic,   copy) NSInteger (^myblock)(BOOL flag);

-(void)someMethodWithBlock:(returnType(^)(parameters))blockName;

- (void)someMethodWithBlock:(NSInteger(^)(BOOL flag))myblock
{
     //code 
    NSInteger index = myblock(YES);
    //处理返回值 index
}

[someObject someMethodWithBlock:^returnType (parameters) {...}];

 [self someMethodWithBlock:^NSInteger(BOOL flag) {
    ///code
    if (flag) return 1;
    return 0;
}];

typedef returnType (^blockName)(parameters);

blockName aBlock = ^returnType(parameters) {...};

typedef  NSInteger (Myblock)(BOOL flag);

//调用
 Myblock block = ^NSInteger(BOOL flag){
    //code
   if(flag)return 1;
   return 0;   
 };

参考:How Do I Declare A Block in Objective-C?

上一篇下一篇

猜你喜欢

热点阅读