gpt4 book ai didi

swift - CoreData合并变更

转载 作者:搜寻专家 更新时间:2023-11-01 05:33:42 28 4
gpt4 key购买 nike

在我的旧项目中,我设置了核心数据存储和模型。在此模型中,我使用 NotificationCenter 来观察 NSManagedObjectContext。每当保存一个上下文时,它就会与其他上下文合并:

NotificationCenter.default.addObserver(self, selector: #selector(didSaveContext), name: .NSManagedObjectContextDidSave, object: nil)

@objc func didSaveContext(notification: Notification) {
guard let sender = notification.object as? NSManagedObjectContext else { return }

if sender === mainContext {
userContext.perform { self.userContext.mergeChanges(fromContextDidSave: notification) }
idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
} else if sender === userContext {
mainContext.perform { self.mainContext.mergeChanges(fromContextDidSave: notification) }
idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
} else if sender === idleContext {
mainContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
userContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
} else {
userContext.perform { self.userContext.mergeChanges(fromContextDidSave: notification) }
mainContext.perform { self.mainContext.mergeChanges(fromContextDidSave: notification) }
idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
}
}

但是从 iOS10 开始,Apple 引入了 NSPersistentContainer,我可以使用:

persistentContainer.viewContext.automaticallyMergesChangesFromParent = true

这是否意味着我不必再使用通知中心来合并更改?

最佳答案

Does this mean I don't have to use the notification center to merge the changes anymore?

不,您必须实现通知并调用 mergeChanges() 来合并更改。

关于swift - CoreData合并变更,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47320233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com