NOTE:我看过类似的问题,但没有找到描述这种情况的问题。
我正在查看 Apple 提供的有关核心数据并发性的以下示例代码(https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/Concurrency.html)
NSArray *jsonArray = …;
NSPersistentContainer *container = self.persistentContainer;
[container performBackgroundTask:^(NSManagedObjectContext *context) {
for (NSDictionary *jsonObject in jsonArray) {
AAAEmployeeMO *mo = [[AAAEmployeeMO alloc] initWithContext:context];
[mo populateFromJSON:jsonObject];
}
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Failure to save context: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
}];
在我的应用程序中,直到用户点击屏幕上的保存按钮后才会启动保存。我该如何解决这个问题,在这种情况下,我应该使用子上下文来代替,其中私有上下文是 VC 的属性?
NSArray *jsonArray = …; //JSON data to be imported into Core Data
NSManagedObjectContext *moc = self.persistentContainer.viewContext; //Our primary context on the main queue
NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[private setParentContext:moc];
[private performBlock:^{
for (NSDictionary *jsonObject in jsonArray) {
NSManagedObject *mo = …; // WHICH CONTEXT TO USE? <<<======
//update MO with data from the dictionary
}
NSError *error = nil;
if (![private save:&error]) {
NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
}
然后,一旦用户点击“保存”,请执行以下操作:
NSManagedObjectContext *moc = self.persistentContainer.viewContext; //Our primary context on the main queue
[moc performBlockAndWait:^{
NSError *error = nil;
if (![moc save:&error]) {
NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
}];
}];
另请注意上面示例中使用哪个 moc 的问题 (
EDIT:我最终做的是立即保存子上下文,以便表只使用viewContext
显示结果。如果用户随后退出而不保存,我会再次从viewContext
。保存按钮仍然存在,但现在仅设置一个标志,指示不删除结果。