我有一個有趣的問題,我似乎無法找到解決方案 - 我有兩個託管對象上下文,'主要'和'支持'。 'Main'使用NSMainQueueConcurrencyType創建,'backing'使用'NSPrivateQueueConcurrencyType'創建。此外,「支持」已被設置爲主要的父項。NSManagedObjectContextDidSaveNotification合併和deletedObjects
我想對支持MOC執行(可能很貴)的寫操作,然後將這些更改(完成時)冒泡到主上下文,從而使我的UI更新由於使用了NSFetchedResultsController。我的問題如下 - 看起來在調用mergeChangesFromContextDidSaveNotification之後,主MOC上的deletedObjects屬性被使用後備隊列的後臺操作中刪除的所有對象填充。
作爲一個例子,下面是一些代碼。
[appDelegate.backingContext performBlock:^{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Parent"];
NSArray *objects = [appDelegate.backingContext executeFetchRequest:fetchRequest error:nil];
for(Parent *parent in objects) {
NSMutableOrderedSet *children = [parent mutableOrderedSetValueForKey:@"children"];
for(Child *child in children) {
[appDelegate.backingContext deleteObject:child];
}
[children removeAllObjects];
for(int i=0;i<3;i++) {
Child *child = [NSEntityDescription insertNewObjectForEntityForName:@"Child"
inManagedObjectContext:appDelegate.backingContext];
child.name = [NSString stringWithFormat:@"Child #%i", i];
[children addObject:child];
}
}
[appDelegate.backingContext save:nil];
}];
,並在我的應用程序委託
- (void)mergeContextChanges:(NSNotification *)notification {
[self.mainContext performBlock:^{
NSLog(@"Before merge: updates - %i, inserts - %i, deletes - %i",
self.mainContext.updatedObjects.count,
self.mainContext.insertedObjects.count,
self.mainContext.deletedObjects.count);
[self.mainContext mergeChangesFromContextDidSaveNotification:notification];
NSLog(@"After merge: updates - %i, inserts - %i, deletes - %i",
self.mainContext.updatedObjects.count,
self.mainContext.insertedObjects.count,
self.mainContext.deletedObjects.count);
}];
}
這裏的日誌說什麼的變化已經合併之後 -
2013-04-03 00:51:40.476 CoreDataTest[41617:c07] Before merge: updates - 0, inserts - 0, deletes - 0
2013-04-03 00:51:40.477 CoreDataTest[41617:c07] After merge: updates - 0, inserts - 0, deletes - 3
你會注意到,在右鍵報道3個對象待定刪除。據我所知,這是不正確的 - 不應該mergeContextChanges:導致(否則完全沒有觸及)上下文的狀態不顯示待處理的更改?這種方法的重點在於更改已經提交給持久存儲。
我在這裏錯過了什麼?
是的 - 經過一番思考後,這種說法很有道理。可以說,如果MOC不是首先對MOC進行重新編程的話,MOC不應該將該對象標記爲待定刪除。我可以明白爲什麼如果這是你想要這樣做 - 它可能出現在關係中,或者有人可能會提到它。但是,如果這完全在MOC的國家內部,我不明白它爲什麼需要標記。 – dpratt
你有沒有找到解決辦法,所以合併不會觸發「hasChanges」標誌? (謝謝!) –