block调用笔记

//ViewController.m

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [self.networkTool loadDatablock:^{
        NSLog(@"在viewController中调用");
    }];

}
@interface NetworkTool : NSObject

- (void)loadData:(void(^)(NSString *))finished;
- (void)loadDatablock:(void(^)())finishedBlock;
@end
@interface NetworkTool ()

//无返回值有参数
@property (nonatomic, copy) void(^finished)(NSString *);
//无返回值无参数 @property (nonatomic, copy)
void(^finishedBlock)(); @end @implementation NetworkTool - (void)loadDatablock:(void(^)())finishedBlock {

       finishedBlock();   

      //打印结果:2016-02-26 15:37:47.163 08-block的回顾[2452:96695] viewController中调用

}
//说明:在viewControll.m中封装block代码,在其他文件创建(无返回值无参数)void((^)())类名,并且调用
//viewControll.m
 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     __weak ViewController *weakSelf = self;
 4     
 5     [self.networkTool loadData:^(NSString *data) {
 6         NSLog(@"在touchesBegan中拿到了数据:%@", data);
 7         
 8         weakSelf.view.backgroundColor = [UIColor yellowColor];
 9     }];
10 }

@implementation NetworkTool

1
- (void)loadData:(void (^)(NSString *))finished 2 { 3 self.finished = finished; 4 dispatch_async(dispatch_get_global_queue(0, 0), ^{ 5 NSLog(@"正在请求数据:%@", [NSThread currentThread]); 6 dispatch_sync(dispatch_get_main_queue(), ^{ 7 NSLog(@"拿到数据,在主线程中回调"); 8 finished(@"json数据"); 9 }); 10 }); 11 }
//打印结果:

2016-02-26 15:57:32.340 08-block的回顾[2605:111971] 正在请求数据:<NSThread: 0x7f9209d309f0>{number = 2, name = (null)}

2016-02-26 15:57:32.341 08-block的回顾[2605:111933] 拿到数据,在主线程中回调

2016-02-26 15:57:32.341 08-block的回顾[2605:111933] touchesBegan中拿到了数据:json数据

//说明:拿到参数finished(所传参数),其他文件调用data

原文地址:https://www.cnblogs.com/xieyunqq/p/5220838.html