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]) {
        //....
    }
 }

 
posted @ 2019-09-19 18:44  久依  阅读(1195)  评论(0编辑  收藏  举报