在 Objective-C 中,遍歷 NSArray 有多種方式。不同方式適合不同情境,例如需要索引、需要並行、需要提前停止,或只是簡單讀取。
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%lu, %@", (unsigned long)idx, obj);
}];
dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index) {
NSLog(@"%zu, %@", index, [arr objectAtIndex:index]);
});
dispatch_apply([arr count], dispatch_get_main_queue(), ^(size_t index) {
NSLog(@"%zu, %@", index, [arr objectAtIndex:index]);
});
for (NSString *str in arr) {
NSLog(@"%@", str);
}
int i = 0;
do {
NSLog(@"%@", [arr objectAtIndex:i]);
i++;
} while (i != [arr count]);
int j = 0;
while (j != [arr count]) {
NSLog(@"%@", [arr objectAtIndex:j]);
j++;
}
for (int m = 0; m != [arr count]; m++) {
NSLog(@"%@", [arr objectAtIndex:m]);
}
dispatch_apply 並行執行時,輸出順序可能不是陣列順序。若使用主線程 dispatch_apply,可能造成主線程阻塞,應避免在 UI 互動中使用。一般情況下,for-in 或 Block 遍歷已足夠。