對於一個數組
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]) { //.... } }