zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Maven笔记之面试题合集
    Maven笔记之核心概念及常用命令
    UML中的关系
    RocketMq核心概念
    linux安装rocketMq(包括安装maven,JDK)
    linux安装JDK,配置环境变量
    ASP.NET Core读取appsettings.json配置文件信息
    ASP.NET Core获取客户端IP地址
    ASP.NET Core根据环境切换NLog配置
    ASP.NET Core使用NLog记录日志
  • 原文地址:https://www.cnblogs.com/xieyunqq/p/5220838.html
Copyright © 2011-2022 走看看