NSMutableArray怎么保证线程安全

多线程去写NSMutableArray,可采用 NSLock 方式,
简单来说就是操作前 lock 操作执行完 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 来实现,个人感觉更高效。

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];
    });
    }

转载:
https://stackoverflow.com/questions/12098011/is-objective-cs-nsmutablearray-thread-safe/17981941#17981941
https://hepinglaosan.github.io/2017/06/20/Thread-Safe-NSMutableArray/

http://blog.csdn.net/kongdeqin/article/details/53171189

https://juejin.im/entry/595ee8a76fb9a06bb47489ef

你可能感兴趣的:(NSMutableArray怎么保证线程安全)