代码块回调

 所谓的代码块的回调,本质上就是类B调用方法Method1(blockParams),类A将代码块的值blockData传入形参blockParams中,(也就是所谓的实现在类A中),类B中使用blockData将具体的参数传入blockData,实现功能。

类B在使用代码块时并不需要知道其具体的值,只是当作一种数据类型使用,真正的值是在类A中,也就是说先使用了类型,具体的值后面传进来,这就是所谓的代码块回调。

 

反过来看就是,代码块作为一种数据类型,正常使用,但是具体的值在以后传入。粗浅的见解

ViewController.m:

 

- (IBAction)BlockStart:(UIButton *)sender {

    

   BlockTest *block = [[BlockTestalloc]init];

    NSLog(@"button click");

    [block DoSomethingWithBlockandRet: ^(int a){

       NSLog(@"接收到参数:%d",a);

       return1;

    }];

    

}

BlockTest.m:

 

//测试有返回值的block调用

 

- (void)DoSomethingWithBlockandRet: (int(^)(int a))completion

{

    NSLog(@"block start");

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

       int reslut = completion(5);

       NSLog(@"%d", reslut);

    });

    

}

 

posted on 2015-07-11 15:51  代码改变宇宙  阅读(211)  评论(0编辑  收藏  举报