gpt4 book ai didi

objective-c - 核心数据: concurency conflict between save and fetch

转载 作者:行者123 更新时间:2023-11-30 12:34:51 26 4
gpt4 key购买 nike

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

    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)")
}
}
}

关于objective-c - 核心数据: concurency conflict between save and fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com