概述:我有一个在后台运行的刷新过程(只使用 performInBackground 就可以了),其中一部分有数据库更新,所以我有一个单独的 MOC 用于后台线程。然后我使用 didSave 通知合并更改,但在 DB/我的 UI 中看不到这些更新。我在保存之前和之后记录了对象本身,我可以看到属性发生了变化,但是在通知调用的方法中,我在接收到的上下文中记录了对象并且它没有更新的值。我知道其他一些事情可能很丑陋,但只是想弄清楚这个核心数据。我以前只有一个 MOC 并且工作正常(非核心数据应该没问题),但我现在重新架构了一些东西以在后台运行,并希望使用单独的 MOC 的指导。
创建上下文、设置通知、设置属性并保存。保存后,值为0
// this creates context with same PSC as main MOC
NSManagedObjectContext *context = [[MyAppDelegate application] temporaryContext];
[[NSNotificationCenter defaultCenter] addObserver:(MyAppDelegate *)[[UIApplication sharedApplication] delegate]
selector:@selector(managedObjectContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:context];
NSLog(@"value is %d", [[myObject email] boolValue]); //value is 1
[myObject setEmail:[NSNumber numberWithBool:![[myObject email] boolValue]]];
NSError *error;
if (![context save:&error]) {
NSLog(@"Error in saving BriefCase object - error:%@" ,error);
}
NSLog(@"value is %d", [[myObject email] boolValue]); //value is 0 now
在这里,我检查了我发送的 MOC,我看到所有值都是 1。所以当合并发生时,没有更新。如果我看到对象在保存后为 0,那么断开连接在哪里?
// Called when a ManagedObjectContext performs save operation
- (void)managedObjectContextDidSave:(NSNotification *)notification {
NSManagedObjectContext *receivedMOC = [notification object];
NSArray *items = [MyObjectClass getAllMyObjectsInManagedObjectContext:receivedMOC];
for (int i=0; i < [items count]; i++) {
NSLog(@"value is %d", [[[items objectAtIndex:i] email] boolValue]);
}
添加上下文创建代码,可能是问题
- (NSManagedObjectContext *)temporaryContext {
NSManagedObjectContext *newContext = [[[NSManagedObjectContext alloc] init] autorelease];
NSPersistentStoreCoordinator *psc = [self.managedObjectContext persistentStoreCoordinator];
[newContext setUndoManager:nil];
[newContext setPersistentStoreCoordinator:psc];
return newContext;