您可以使用以下代码在多线程中管理 NSManagedObjectContext
- (void)mergeChanges:(NSNotification*)notification
{
NSLog(@"[mergeChanges] enter");
// save changes to manageObjectContext on main thread
AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
[[theDelegate managedObjectContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
NSLog(@"[mergeChanges] leave");
}
- (NSManagedObjectContext*)startThreadContext
{
AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
[newMoc setPersistentStoreCoordinator:[theDelegate persistentStoreCoordinator]];
// Register for context save changes notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:newMoc];
return newMoc;
}
- (void)stopThreadContext:(NSManagedObjectContext*)context
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:context];
}
在线程上下文的开头,您可以调用
-(NSManagedObjectContext*)startThreadContext
并在线程中使用新的 NSManagedObjectContext ,您可以在线程完成后删除 NSManagedObjectContext 。当您保存新的 NSManagedObjectContext 时,它会通知主线程的托管对象上下文以保存更改。