关于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中使用。 这个还没有仔细研究。