简体   繁体   English

iOS / Objective-C:在后台线程中保存到核心数据

[英]iOS/Objective-C: Save to core data in background thread

I am trying to follow this Apple example code for best practice saving to core data in background that includes this code: 我正在尝试遵循此Apple示例代码,以获取最佳实践,以在后台保存到包含以下代码的核心数据:

NSArray *jsonArray = …; //JSON data to be imported into Core Data
NSManagedObjectContext *moc = …; //Our primary context on the main queue

NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[private setParentContext:moc];

My main MOC is save in a property. 我的主要MOC保存在属性中。 However, whether I alloc init a fresh MOC or use the one in the property,I get the error: 但是,无论我分配一个新的MOC还是在该属性中使用一个,都会出现以下错误:

'Parent NSManagedObjectContext must use either NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType.'
*** First throw call stack:

The solution to this is said to specify the concurrency type for the MOC as follows: 据说此解决方案指定MOC的并发类型,如下所示:

managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

Should this be done in the main core data stack? 是否应该在主核心数据堆栈中完成? Or do you create a new MOC? 还是创建一个新的MOC? I tried creating a new MOC and got an error that the MOC was null. 我尝试创建一个新的MOC,但收到一个错误消息,说MOC为空。 It also seems redundant to create a second MOC that with the private one makes three. 创建第二个MOC(由私有MOC生成三个MOC)似乎也很多余。 On the other hand I am afraid to change the main core data stack as it may throw other things off in the app. 另一方面,我担心更改主核心数据堆栈,因为它可能会使应用程序中的其他内容丢掉。

What is best way to fix this? 解决此问题的最佳方法是什么?

The main MOC should be the child of the background private moc instead of the otherway around. 主MOC应该是后台私有Moc的子级,而不是相反。 Whenever you save the main moc, the private moc would get updated (thus you need to set the mergePolicy) and then saved to disk. 每当您保存主Moc时,私有Moc都会被更新(因此您需要设置mergePolicy),然后保存到磁盘。 In this scenario you don't need more than 2 mocs. 在这种情况下,您不需要2个以上的Mocs。

Because the save will be in the background thread, your code will run smoother in the main thread. 因为保存将在后台线程中进行,所以您的代码将在主线程中更流畅地运行。

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; // primary context on the main queue
moc.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

NSManagedObjectContext *privateMoc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
privateMoc.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
[moc setParentContext:privateMoc];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM