IOS中得block代码块的定义及使用

来源:互联网 发布:国家大数据行动计划 编辑:程序博客网 时间:2024/05/17 21:39
现在的无论是框架还是项目中,越来越多的使用block代码块。
个人觉得:第一可以使代码看起来更简单明了,第二可以取代以前的delegate使代码的逻辑看起来更清晰。

借一张图表达基本定义:


(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)(10 * 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
#import "HttpReq.h"@implementation HttpReq-(void)sendHttpReqUseUrl:(NSString*)url withBlock:(HttpSendBlock) block{    //……………发送请求并获取返回结果……………    NSDictionary *dic = [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"name",@"state", nil] forKeys:[NSArray arrayWithObjects:@"wdl",@"ok", nil]];        //返回请求结果    block(dic);}@end
在一个Controller调用发送HTTP请求。

- (void)viewDidLoad {    [super viewDidLoad];    HttpReq *req = [[HttpReq alloc]init];    [req sendHttpReqUseUrl:@"www.baidu.com" withBlock:^(NSDictionary *dict) {        NSLog(@"dict : %@",dict.description);    }];}

看起来比较清晰,如果使用delegate的形势就相对比较繁琐一些,需要定义@optional,需要引用代理,实现代理,通过代理将结果返回回来。





参考:

http://blog.csdn.net/totogo2010/article/details/7839061

http://blog.csdn.net/mobanchengshuang/article/details/11751671

1 0
原创粉丝点击