`
ydbc
  • 浏览: 718435 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

ios 全面解析block

阅读更多
Block
Block变量格式: 
返回值类型(不可省略, 最少void,没有()) + (^变量名称) + (参数) (不可省略, 至少()).

无参数无返回值
    void (^noParamBlock)() = ^(){NSLog(@"this is a noParamBlcok!");};
    noParamBlock();
    
    void (^voidParamBlock)(void)= ^(void){NSLog(@"this is a voidParamBlock!");};
    voidParamBlock();
    
    void (^blockName)();
    blockName = ^{NSLog(@"this is a block!");};
    blockName();

有参数无返回值
    void (^hasParamBlock)(int) = ^(int param){NSLog(@"param is %d",param);};
    hasParamBlock(10);

有参数有返回值
    int (^hasReturnValueBlock)(int,int) = ^(int param1,int param2){ return param1 + param2;};
    NSLog(@"return value %d",hasReturnValueBlock(10,10));

@property Block
typedef int (^MyBlock) (int,int);
@property (nonatomic, copy) int (^cBlock)(int num1,int num2);
@property (nonatomic, copy) MyBlock block;

xx.cBlock  =   ^(int num1,int num2){return num1*num2;};
xx.block = ^(int num1,int num2){return num1*num2;};

Block作为参数
- (void)funWithBlock:(NSString* (^)(int ,NSString * ))blockName1 anotherBlock:(MyBlock)blockName2{
    
    NSLog(@"block1->%@",blockName1(4,@"str"));
    NSLog(@"block2->%d",blockName2(1,5));  
}
   
[self funWithBlock:^(int num,NSString *str){
        return [NSString stringWithFormat:@"%d++%@",num,str];
    } anotherBlock:block];
  
Block作为返回值
- (int (^)(int ,int))funBlockBack{
    return ^(int num1,int num2){
        return num1+num2;
    };
}

NSLog(@"blockBack-> %d",[self funBlockBack](1,7));

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics