EnumerateObjectsUsingBlock

最近在github上查看老外的代码时,发现老外遍历时都爱用

-(void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block

这个方法,查阅资料得知遍历字典和量大的数组和遍历字典时性能比 for in 好,且代码更加优雅;对于单个数组使用for in 新能更好

遍历字典时

Block版本的字典遍历可以同时取key和value而for in只能取key再手动取value

NSDictionary *dict = @{@"a": @"1", @"b": @"2"};

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)  {

  NSLog(@"key: %@, value: %@", key, obj);

}];

对于耗时且顺序无关的遍历,使用并发版本的blck,

-(void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block

NSDictionary *dict = @{@"a": @"1", @"b": @"2"};
[dict enumerateKeysAndObjectsWithOptions:NSEnumerationReverse usingBlock:^(id key,id obj,BOOL *stop) {

    NSLog(@"key:%@-----value:%@----",key,obj);

}];

遍历数组时

NSArray*array =@[@"1",@"2",@"3",@"4",@"5"];

[array enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL * stop) {

    NSLog(@"1:%@----%d",obj,(int)idx);

}];

并发遍历数组

[array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj,NSUInteger idx,BOOL * stop) {

    NSLog(@"2:%@----%d",obj,(int)idx);

}];

倒序遍历数组

for (NSString *string in [array reverseObjectEnumerator]) {

    NSLog(@"12:%@----",string);

}

[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj,NSUInteger idx,BOOL* stop) {

    NSLog(@"13:%@----%d",obj,(int)idx);

}];

你可能感兴趣的:(EnumerateObjectsUsingBlock)