您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 陣列遍歷的七種方式

編輯:iOS 開發綜合

在 Objective-C 中,遍歷 NSArray 有多種方式。不同方式適合不同情境,例如需要索引、需要並行、需要提前停止,或只是簡單讀取。

1. Block 遍歷

[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"%lu, %@", (unsigned long)idx, obj);
}];

2. dispatch_apply 並行遍歷

dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index) {
    NSLog(@"%zu, %@", index, [arr objectAtIndex:index]);
});

3. dispatch_apply 主線程遍歷

dispatch_apply([arr count], dispatch_get_main_queue(), ^(size_t index) {
    NSLog(@"%zu, %@", index, [arr objectAtIndex:index]);
});

4. for-in 快速枚舉

for (NSString *str in arr) {
    NSLog(@"%@", str);
}

5. do-while 遍歷

int i = 0;
do {
    NSLog(@"%@", [arr objectAtIndex:i]);
    i++;
} while (i != [arr count]);

6. while 遍歷

int j = 0;
while (j != [arr count]) {
    NSLog(@"%@", [arr objectAtIndex:j]);
    j++;
}

7. 一般 for 迴圈

for (int m = 0; m != [arr count]; m++) {
    NSLog(@"%@", [arr objectAtIndex:m]);
}

8. 注意事項

dispatch_apply 並行執行時,輸出順序可能不是陣列順序。若使用主線程 dispatch_apply,可能造成主線程阻塞,應避免在 UI 互動中使用。一般情況下,for-in 或 Block 遍歷已足夠。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved