我已经试着修复这起事故将近一周了.应用程序崩溃,没有任何异常或堆栈跟踪.在僵尸模式下运行仪器时,应用程序不会以任何方式崩溃.

我有一个在不同线程上被调用的方法.

[self.mutableArray removeAllObjects];

具有

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

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

@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
        }
    }
}

Is this problem 具有 NSMutableArray not being thread-safe?

推荐答案

它不是线程安全的,如果需要从另一个线程修改可变数组,则应使用NSLock以确保一切按计划进行:

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

[...] 

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

Objective-c相关问答推荐

在 Objective-C 中完成受保护属性的解决方法

单例实例与类方法

UITextField secureTextEntry 带有自定义字体的项目符号?

通过指针算术访问数组值与 C 中的下标

如何测试 NSCFBolean 值?

核心数据独特属性

NSInternalInconsistencyException', reason: '试图将第 0 行插入第 0 节,但更新后第 0 节只有 0 行'

多个 WKWebView 之间的 Cookie 共享

Objective-C 中的正式协议和非正式协议有什么区别?

如何更改图像 tintColor

Objective-C:如何使用 BOOL 类型的参数调用 performSelector?

Xcode:可以为协议接口所需的方法自动创建存根吗?

在 iOS 中创建带有 URL 的 UIImage

未知类型名称类;您指的是 'Class' 吗?

在 NSArray 中查找最大数值

如何像在 Spotify 的播放器中一样创建居中的 UICollectionView

通过点击状态栏滚动到 UITableView 的顶部

Xcode没有编译任何项目? 'clang 失败,退出代码 255'

如何在 NSUserDefaults 中保存 NSMutablearray

找出窗口中的 UIBarButtonItem 框架?