iOS中Block声明方式

如何在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;
}];
  • C函数的参数:

    voidSomeFunctionWithBlock( returnType(^blockName)(parameterTypes));

    void someMethodWichBlock(NSInteger(^myblock)(BOOL)){
      //code 
     NSInteger index = myblock(YES);
      //处理返回值 index
    };    
    
  • typedef:

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?

你可能感兴趣的:(iOS中Block声明方式)