我使用嵌套的托管对象上下文进行核心数据保存。我有一个writerContext,它将更改写入持久性存储,以及一个mainContext,它是writerContext的子级。主上下文用于我的获取结果控制器和其他UI相关任务。然后我有一个workerContext,它是mainContext的子代。 workerContext用于从Web服务进行保存。
从我读过的所有内容中,当保存工作者上下文时,workerContext的更改应自动传播到mainContext,然后在保存mainContext时传递到writerContext。我的数据被保存到商店,因此我知道所有内容都通过mainContext传播,但我的获取结果控制器看不到更改。有谁知道为什么我的获取结果控制器委托不会看到更改并更新UI?
我发布了以下代码,用于核心数据堆栈的相关部分。
// Create Main Context
mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
mainContext.parentContext = writerContext
mainContext.name="mainContext"
// mainContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
mainContext.mergePolicy = NSMergePolicy(mergeType:NSMergePolicyType.MergeByPropertyStoreTrumpMergePolicyType )
func saveMainContext (mainContext:NSManagedObjectContext) {
print("+++++++++++ \(__FUNCTION__) ++++++++++++")
mainContext.performBlockAndWait{ () -> Void in
let wc=mainContext.updatedObjects
print("1-Main thread\(NSThread.isMainThread())")
print("mainContext.changedObjects=\(wc.count)")
if mainContext.hasChanges {
do {
print("try")
try mainContext.save()
self.saveWriterContext(mainContext.parentContext!)
} catch let error as NSError {
NSLog("Unresolved error \(error), \(error.userInfo)")
// Handle Error
} catch {
print("Something went wrong!")
}
}
}
}
func saveWriterContext (writerContext:NSManagedObjectContext) {
print("+++++++++++ \(__FUNCTION__) ++++++++++++")
writerContext.performBlock{ () -> Void in
let wc=writerContext.updatedObjects
print("writerContext.changedObjects=\(wc.count)")
if writerContext.hasChanges {
do {
print("try")
try writerContext.save()
} catch let error as NSError {
NSLog("Unresolved error \(error), \(error.userInfo)")
// Handle Error
} catch {
print("Something went wrong!")
}
}
}
}
func saveWorkerContext(workerContext:NSManagedObjectContext) {
print("+++++++++++ \(__FUNCTION__) ++++++++++++")
workerContext.performBlockAndWait{
let wc=workerContext.updatedObjects
print("workerContext.changedObjects=\(wc.count)")
if workerContext.hasChanges {
do {
print("try")
try workerContext.save()
self.saveMainContext(workerContext.parentContext!)
} catch let error as NSError {
NSLog("Unresolved error \(error), \(error.userInfo)")
// Handle Error
} catch {
print("Something went wrong!")
}
}
}
}
我也尝试合并contextDidSaveContext(notification: NSNotification)
self.mainContext.mergeChangesFromContextDidSaveNotification(notification)
任何帮助弄清楚为什么取出的结果控制器没有更新将不胜感激。