我最喜欢用的代码块 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(@{});

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EugeneLaw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值