Objective-C中3种枚举比较及KVO两个小技巧
一:oc的3种枚举
- for循环
- for in
- 枚举块
如代码
NSUInteger totalCount = 10000; NSMutableArray *array = [NSMutableArray arrayWithCapacity:totalCount]; //create an array including 10000 elements for (int i = 0; i<totalCount; i++) { array[i] = [@(i) stringValue]; } //C Language For Loop Enumeration CFTimeInterval start1 = CACurrentMediaTime(); for (int j = 0; j< totalCount; j++) { NSLog(@"%@",array[j]); } CFTimeInterval end1 = CACurrentMediaTime(); NSLog(@"C Language For Loop method %f",end1 - start1); //Objective-C Fast Enumeration CFTimeInterval start2 = CACurrentMediaTime(); for (NSString *string in array) { NSLog(@"%@",string); } CFTimeInterval end2 = CACurrentMediaTime(); NSLog(@"Objective-C Fast Enumeration method %f",end2 - start2); //Objective-C Block Enumeration CFTimeInterval start3 = CACurrentMediaTime(); [array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) { NSLog(@"%@",obj); }]; CFTimeInterval end3 = CACurrentMediaTime(); NSLog(@"Objective-C Block Enumeration method %f",end3 - start3);
打印结果:
综上:块是最快的!
二:kvc两个小技巧
1:keyPath取嵌套字典的值;
2: kvc消息的高级传递
转自:http://nijino.cn/blog/2013/07/02/using-kvc/
http://nijino.cn/blog/2014/03/11/comparison-for-3-enumeration-methods-in-objective-c/