Objective-C的NSMutableArray是否是线程安全的? [英] Is Objective-C's NSMutableArray thread-safe?

查看:262
本文介绍了Objective-C的NSMutableArray是否是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图解决这个崩溃已近一周了。应用程序崩溃,没有任何异常或堆栈跟踪。在僵尸模式下运行仪器时,应用程序不会以任何方式崩溃。

I've been trying to fix this crash for almost a week. The application crashes without any exception or stack-trace. The application does not crash in any way while running through instruments in zombie mode.

我有一个在不同线程上调用的方法。
修复崩溃的解决方案是替换

I have a method that gets called on a different thread. The solution that fixed the crash was replacing

[self.mutableArray removeAllObjects];

with

dispatch_async(dispatch_get_main_queue(), ^{
    [self.searchResult removeAllObjects];
});

我认为这可能是一个时间问题,所以我尝试同步它,但它仍然崩溃:

I thought it might be a timing issue, so I tried to synchronize it, but it still crashed:

@synchronized(self)
{
    [self.searchResult removeAllObjects];
}

这是代码

- (void)populateItems
{
   // Cancel if already exists  
   [self.searchThread cancel];

   self.searchThread = [[NSThread alloc] initWithTarget:self
                                               selector:@selector(populateItemsinBackground)
                                                 object:nil];

    [self.searchThread start];
}


- (void)populateItemsinBackground
{
    @autoreleasepool
    {
        if ([[NSThread currentThread] isCancelled])
            [NSThread exit];

        [self.mutableArray removeAllObjects];

        // Populate data here into mutable array

        for (loop here)
        {
            if ([[NSThread currentThread] isCancelled])
                [NSThread exit];

            // Add items to mutableArray
        }
    }
}

NSMutableArray的这个问题是不是线程安全的?

Is this problem with NSMutableArray not being thread-safe?

推荐答案

否。

它不是线程安全的,如果你需要从另一个线程修改你的可变数组,你应该使用 NSLock 来确保一切顺利计划:

It is not thread safe and if you need to modify your mutable array from another thread you should use NSLock to ensure everything goes as planned:

NSLock *arrayLock = [[NSLock alloc] init];

[...] 

[arrayLock lock]; // NSMutableArray isn't thread-safe
[myMutableArray addObject:@"something"];
[myMutableArray removeObjectAtIndex:5];
[arrayLock unlock];

这篇关于Objective-C的NSMutableArray是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆