我有一个使用 Core Data 的应用程序。这是我第一次使用它,所以我使用 Apple 在 AppDelegate.m
中提供的相同核心数据堆栈。 .
我面临的问题描述如下:
我有一个名为 firstSaver
的方法它执行以下操作:
+(void) firstSaver {
// 1) get some values from system
// 2) do some processing on those values ( This takes considerable time)
// 3) create a NSManagedObject instance of entity A ,say mObj ,by filling in the processed values. I create multiple objects. In this step, I use the main managedObjectContext that is provided by the AppDelegate to me.
// 4) pass this NSManagedObject to secondSaver like :
[self secondSaver : mObj];
// 5) save the managedObjectContext.
}
第二种方法的工作原理是:
+(void) secondSaver : (NSManagedObject *)someObj {
// 1) again fetch some values, this too takes considerable time.
// 2) create a NSManagedObject which is instance of entity B, fill the processed values, attach this instance to the someObj instance.
return;
}
请注意,A 通过一对多关系与 B 相关,即 A 包含
NSSet
B.如图所示,这两个调用需要相当长的时间才能完成,并且会卡住 UI。我不希望它发生,因此我创建了一个序列
dispatch_queue
并调用firstSaver
使用 dipatch_async
.问题是作为
NSManagedObjectContext
的实例已在主线程上创建,如果我在 dispatch_async
中访问它,结果为 EXEC_BAD_ACCESS
.处理这种情况并使用适当的托管对象上下文来处理多线程的正确方法可能是什么?任何帮助将不胜感激。
最佳答案
您应该创建新的子托管对象上下文以使用,私有(private)队列类型和主上下文作为父级。您的所有逻辑都应该在 performBlockAndWait:
中这就是您进行长查询并创建新对象的地方。
使用 mObj
在这里你需要得到它的objectID
然后使用 existingObjectWithID:error:
在子上下文中获取适当的版本。然后,您可以在正确的上下文中将新对象连接到现有对象。
完成后,保存子上下文,然后使用 performBlock
在主要上下文上并保存它。
// move to background thread
// create child
// set parent
// perform block and wait on new context
// find the existing object for mObj ID
// search, create, associate
// save
// perform block on the main context
// save
关于ios - 如何在多个线程上处理 NSManagedObjectContext 和 NSManagedObject 创建和编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33803267/