block的定义及使用

(1)最基础的用法案例,我们可以把block理解为一段类似变量一样的可执行函数代码片段:

       void (^printBlock)(NSString *x);    

       printBlock = ^(NSString* str)    

        {    

        NSLog(@"print:%@", str);    

       };    

       printBlock(@"hello world!");    

(2)由于是变量,所以比方法等可以更灵活的使用,因为可以把block当做一个变量传入到另一个方法。

        - (void)viewDidLoad {  

         [super viewDidLoad];  

           NSLog(@"我在玩手机");  

           NSLog(@"手机没电了");  

         [self chargeMyIphone:^{  

           NSLog(@"去逛街");  

         }];  

         NSLog(@"我在看电视");  

         }  

      -(void)chargeMyIphone:(void(^)(void))finishBlock {  

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

          NSLog(@"电充好了");  

          finishBlock();  

      });  

  }  

(3)上述方法是在单个类中执行的,如果在两个类中使用就能更加显现出其功能。可以用来取代代理,可以是逻辑变得清晰。如此处模拟一个发送HTTP请求的类。

       

        #import <Foundation/Foundation.h>  

        typedef void(^HttpSendBlock)(NSDictionary *dict);  @interface HttpReq : NSObject  

        -(void)sendHttpReqUseUrl:(NSString*)url withBlock:(HttpSendBlock) block;

        @end

原文地址:https://www.cnblogs.com/liYongJun0526/p/4869581.html