我正在處理的情況是,如果存在將被刪除的對象會通過級聯刪除關係導致指數級刪除的情況。通過這種方式,刪除這些對象中的20個可能會導致〜3,000個對象最終被刪除。如果使用主要上下文執行,這會導致非常緩慢的保存。在覈心數據中處理大量刪除/插入
爲了解決這個問題,我創建一個使用相同的持久性存儲爲主要背景下,「工人」背景下,更改那裏,然後保存工人背景和合並與主背景下這些變化:
NSManagedObjectContext *workerContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
workerContext.persistentStoreCoordinator = mainContext.persistentStoreCoordinator;
[notificationCenter addObserver:self selector:@selector(workerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:workerContext];
// Here I do a 'superficial' deletion on the main context, so the UI updates,
// but do the actual deletion on the worker context. Then I save the worker context:
[workerContext save:nil];
// Which fires spawnedWorkerContextDidSave:, where I merge changes to the main context:
[mainContext performBlockAndWait:^{
[mainContext mergeChangesFromContextDidSaveNotification:notification];
}];
我的問題是:處理這些大批量刪除批次的最常用方法是什麼?我的方法有什麼缺陷嗎?另外,合併會在主線程上造成一些小的延遲,但是當我執行刪除操作並保存在主線程中時,它並沒有接近它的位置。
嘗試在主線程中不使用GCD。 –
@SunilSingh這就是我在這裏所做的。工作者上下文使用它自己的線程。 – mattsven