enumerateObjects遍历方法详解

来源:互联网 发布:广州软件外包 编辑:程序博客网 时间:2024/05/18 22:15

在之前的文章中转载过iOS中集合遍历方法的比较和技巧, 有兴趣的可以了解一下. 本文主要是介绍enumerateObjects遍历方法.

ios中常用的遍历运算方法

遍历的目的是获取集合中的某个对象或执行某个操作,所以能满足这个条件的方法都可以作为备选: 
- 经典for循环 
- for in (NSFastEnumeration),若不熟悉可以参考《nshipster介绍NSFastEnumeration的文章》 
- makeObjectsPerformSelector 
- kvc集合运算符 
- enumerateObjectsUsingBlock 
- enumerateObjectsWithOptions(NSEnumerationConcurrent) 
- dispatch_apply

enumerateObjects遍历方法

在enumerateObjects遍历有3个方法, 这个遍历方式的优点: 
1.遍历顺序有正序/倒序/并发混序三种, 可根据枚举值控制比 for循环方便许多. 
2.遍历中自带 *stop参数, 跳出方便. 
3.可以在遍历的 block中增删数据, 比 forin遍历方便许多 
4.在庞大的数据量下, 此方式是比 for循环, forin 等方式,要快许多的方式.在其执行过程中可以利用到多核cpu的优势

正序遍历方法

    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];    //按顺序对 arr 进行遍历    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        NSLog(@"%ld===%@",idx,obj);        if (idx == 4){            *stop = YES;        }    }];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

打印结果:

0===11===22===33===44===5
  • 1
  • 2
  • 3
  • 4
  • 5

倒序/并发混序遍历方法

option参数: 
//NSEnumerationReverse 倒序执行 
//NSEnumerationConcurrent 并行发生, 并发混序

    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];    [arr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        NSLog(@"%ld===%@",idx,obj);        if (idx == 3){            *stop = YES;        }    }];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

打印结果:

0===14===51===22===33===4
  • 1
  • 2
  • 3
  • 4
  • 5

根据indexSet进行倒序/并发混序的遍历方法

(NSIndexSet *)s参数: 需要遍历的下标 set

NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];    //根据indexSet 中包含的下标, 在 arr 中进行遍历//    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(2, 2)];    [arr enumerateObjectsAtIndexes:indexSet options:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        NSLog(@"%ld===%@",idx,obj);    }];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

打印结果:

3===42===3
  • 1
  • 2
原创粉丝点击