iOS数组遍历

对于一个数组

    NSArray *array = @[@"111",@"222",@"333",@"444",@"555",@"666",@"777",@"888",@"999",];

    NSInteger count =array.count;

1.for循环

for (NSInteger i=0; i<count; i++) { NSLog(@"%@----%@",array[i],[NSThread currentThread]); } 

2.for in快速枚举

for (NSString *string in array) { NSLog(@"%@----%@",string,[NSThread currentThread]); } 

集合中对象数很多的情况下,for in 的遍历速度非常之快。但小规模的遍历 还没for循环快。

3. 枚举器NSEnumerator

    // 向数组请求枚举器
    NSEnumerator *enumer = [array objectEnumerator]; // 正序 NSEnumerator *enumer2 = [array reverseObjectEnumerator]; // 倒序 id obj; while ( obj = [enumer nextObject]) { // nextObject为nil,结束循环 // 不可对array的元素进行增 删 NSLog(@"%@----%@",obj,[NSThread currentThread]); } 

4. enumerateObjectsUsingBlock方法

    // 顺序遍历
    [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSLog(@"%@----%@",array[idx],[NSThread currentThread]); if (idx == 5) { *stop = YES; // 停止遍历 } }]; // 倒序遍历 [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSLog(@"%@----%@",array[idx],[NSThread currentThread]); if (idx == 5) { *stop = YES; // 停止遍历 } }]; 

Block内代码可以并发执行。

字典情况下

    NSDictionary * dic = [NSDictionary dictionary]; [dic enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSLog(@"value for key %@ is %@ ", key, value); if ([@"key2" isEqualToString:key]) { *stop = YES; } }]; 

遍历字典类型时,推荐使用。字典遍历可以同时取allkeys和allvalues中的元素。

5.多线程dispatch_apply

// 并行队列
dispatch_queue_t queue = dispatch_queue_create("zzz", DISPATCH_QUEUE_CONCURRENT);
    
dispatch_apply(count, queue, ^(size_t index) {
    NSLog(@"%@----%@",array[index],[NSThread currentThread]);
});
 

适用于 处理每一次循环都有耗时任务的数组遍历。

6.NSSet

 NSArray *arr1 = ....; NSArray *arr2 =....; NSSet *aaaSet = [NSSet setWithArray:arr2]; for (NSUInteger i = 0; i < arr1.count; ++i) { UIView *targetView = arr1[i]; if ([aaaSet containsObject:targetView]) { //.... } } 
 

转载于:https://www.cnblogs.com/jiuyi/p/11551708.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值