多線程去寫NSMutableArray,可采用 NSLock 方式,
簡單來說就是操作前 lock 操作執(zhí)行完 unlock。
但注意,每個讀寫的地方都要保證用同一個 NSLock進行操作。
NSLock *arrayLock = [[NSLock alloc] init];
[...]
[arrayLock lock]; // NSMutableArray isn't thread-safe
[myMutableArray addObject:@"something"];
[myMutableArray removeObjectAtIndex:5];
[arrayLock unlock];
另一種方式是利用 GCD 的 concurrent queue 來實現(xiàn),個人感覺更高效。
dispatch_queue_t concurrent_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
For read:
- (id)objectAtIndex:(NSUInteger)index {
__block id obj;
dispatch_sync(self.concurrent_queue, ^{
obj = [self.searchResult objectAtIndex:index];
});
return obj;
}
For insert:
- (void)insertObject:(id)obj atIndex:(NSUInteger)index {
dispatch_barrier_async(self.concurrent_queue, ^{
[self.searchResult insertObject:obj atIndex:index];
});
}
For remove:
- (void)removeObjectAtIndex:(NSUInteger)index {
dispatch_barrier_async(self.concurrent_queue, ^{
[self.searchResult removeObjectAtIndex:index];
});
}
轉(zhuǎn)載:
https://stackoverflow.com/questions/12098011/is-objective-cs-nsmutablearray-thread-safe/17981941#17981941
https://hepinglaosan.github.io/2017/06/20/Thread-Safe-NSMutableArray/