Block的优点

关于Block的语法我就不讲了,请看这篇文章

刚开始学习block的时候,觉得比较奇怪,block到底有什么用?它和函数有什么区别?经过一番学习,主要是这篇文章,发现block有以下几个地方最有用:

1.简化的回调过程,不用再实现并调用某个函数如Notification的方法,以前是这么写:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)notification {   
// Notification-handling code goes here.   
}

现在可以这么写:
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification 
    object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif)

或者UIView动画结束时的操作:

animateWithDuration:delay:options:animations:completion:

代替

setAnimationDidStopSelector:(SEL)selector

2.用作枚举类型遍历的方法 ,即相当于

for (id item in collection) {   
    // Code to operate on each item in turn.   
}


NSString *area = @"Europe";   
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];   
NSMutableArray *areaArray = [NSMutableArray arrayWithCapacity:1];   
NSIndexSet *areaIndexes = [timeZoneNames indexesOfObjectsWithOptions:NSEnumerationConcurrent   passingTest:^(id obj, NSUInteger idx, BOOL *stop) {   NSString *tmpStr = (NSString *)obj;   
return [tmpStr hasPrefix:area];   
}];   
NSArray *tmpArray = [timeZoneNames objectsAtIndexes:areaIndexes];   
[tmpArray enumerateObjectsWithOptions:NSEnumerationConcurrent|NSEnumerationReverse   
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {   
[areaArray addObject:[obj substringFromIndex:[area length]+1]];   
}];   
NSLog(@"Cities in %@ time zone:%@", area, areaArray); 

3.排序

NSComparator finderSort = ^(id string1, id string2) {   
        NSRange string1Range = NSMakeRange(0, [string1 length]);   
        return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];   
};   
NSLog(@"finderSort: %@", [stringsArray sortedArrayUsingComparator:finderSort]);  

4.并发,在GCD和NSOperationQueue中使用。 这个还没有仔细研究。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值