我最喜欢用的代码块 BLOCK

    在iOS中有代理回调、通知、代码块等传递响应链的方式,代理和通知我总觉得麻烦,而BLOCK的用法却经常让我有一种莫名的爽感。

    BLOCK在成员属性中可以这样定义:@property (nonatomic, copy) <#void#>(^<#block name#>)(<#param...#>);

    格式是:@property(nonatomic, copy) 返回类型 (^ 代码块名称) (参数类型 参数名 ...)

    TIPS:在成员属性上方添加注释,可以在引用该成员变量的过程中提示出来。    

    BLOCK在作用于的定义格式是:    

self.block = ^(NSDictionary *info) {
    //code
};

    BLOCK在作用于调用的格式是:

self.block(params...);

    用法介绍完,再介绍用处:

>开发SDK时传递响应链
    以Refresh控件为例,用户拖动TableView刷新控件时,SDK检查存在则调用使用者预先设置好的成员属性记录的代码块中的代码,完成网络请求。

self.mTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //code
}];



>封装网络请求
    网络请求完成后,我们也会封装网络请求的相关代码,只留下一个block作为回调的窗口执行后面的事件。

[AFNManager get:API(URL_xxx_xxx, ACTION_xxx_xxx) 
 params:@{@"id":requestID} success:^(id  _Nonnull responseObject) {
    if (REQUEST_ABORTED) return;
    //code
}];



>系统API也大量使用BLOCK来简化代码使用

NSArray *sort = [self.dataSource sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *statisid1 = obj1[@"statisid"];
        NSString *statisid2 = obj2[@"statisid"];
        return [@(statisid1.intValue) compare:@(statisid2.intValue)]; //升序
    }];
[self.dataSource removeAllObjects];



>封装UI控件并留下控件交互回调的BLOCK
    当前文件在某ViewController中,自定义控件在独立文件中,控件被交互后调用类创建时候保存下来的block属性,即可让事件响应链回到某ViewController中。
[[SelectControl selectControl:choices defaultIndex:currendIndex otherInfo:otherInfo callback:^(NSDictionary * _Nonnull info) {
    //code
}] show];



>封装重复代码

如:相似代码在两个循环里面出现,有大量相似之处又不完全一样

for (int i = 0; i < 9; i ++) {
    //other code, not the same 1
    //the same code
}
    
for (int i = 0; i < 9; i ++) {
    //the same code
    //other code, not the same 2
}

那么就适合用block进行提炼:

void (^block)(NSDictionary *params) = ^(NSDictionary *params) {
    //the same code
};
    
for (int i = 0; i < 9; i ++) {
    //other code, not the same 1
    block(@{@"param1":@"x"});
}
    
for (int i = 0; i < 9; i ++) {
    block(@{@"param2":@"x"});
    //other code, not the same 2
}



    代码块作用域中修改作用域外的属性:(这点用过的应该很熟了)

__block NSDictionary *param = nil;
    
void (^block)(NSDictionary *params) = ^(NSDictionary *params) {
    param = [NSDictionary new];
 };

block(@{});

    代码块的用途全靠想象力,灵活自由强大,没提到的就等着各位发掘了。

扫描二维码关注公众号,回复: 2317896 查看本文章

    代码块的定义格式多少有些别扭,不要忘了把代码片段存起来快速调用,提高编程效率。

猜你喜欢

转载自blog.csdn.net/weixin_40287666/article/details/81125842