核心数据:save和fetch的并发冲突

Core data: concurency conflict between save and fetch

这两个函数调用似乎有冲突:

    MagicalRecord.save({ (localContext) in
        let items = NewsItem.staleNewsItems(in: localContext)
        if ((items?.count)! > 0){
            items?.forEach({ (item) in
                if let object = item as? NSManagedObject {
                    object.mr_deleteEntity(in: localContext)
                }
            })
        }
    })

- (void) buildAndFetchFRCsInContext:(NSManagedObjectContext*)context {
self.newsItemsFRC = [self buildFetchResultsControllerForClass:[NewsItem class] sortedBy:@"id" withPredicate:nil inContext:context];

[context performBlock:^{
    __unused NSDate* start = [NSDate date];
    NSError* error;

    [self.newsItemsFRC performFetch:&error]; // this line crashes
    [self calculateAndBroadcastCounts];
}];
}

这个保存调用线程安全吗?如果是这样,是什么导致这两个函数相互崩溃?

问题是我在创建它们的上下文之外修改新闻项。因此,为了解决这个问题,我不得不将代码移至主线程。我从使用神奇的记录保存切换到只使用 performBlockAndWait,它保证在调用线程上 运行:

private static func cleanUpNewsItems() -> Void {
    let context = NSManagedObjectContext.mr_()
    context.performAndWait { 
        var itemsToDelete = [NSManagedObject]()
        if let items = NewsItem.staleNewsItems(in: context) {
            items.forEach({ (item) in
                itemsToDelete.append(item as! NSManagedObject)
            })
        }
        for item in itemsToDelete {
            context.delete(item)
        }
        do {
            try context.save()
        } catch let error as NSError {
            print("Error While Deleting Note: \(error.userInfo)")
        }
    }
}