如何管理临时保存的 CoreData? 一旦我做了这样的事情:
var myClass: MyClass = NSEntityDescription.insertNewObjectForEntityForName("MyClass", inManagedObjectContext: (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!) as MyClass
它是我的 managedObjectContext 的一部分,当我执行 context.save(nil)
时将被保存
有没有办法在不弄乱我当前上下文的情况下获取 NSManagedObject 类的对象。
换句话说:我想要一些可选对象,当我没有显式保存它们时,它们最终就不会被使用,我想要一些我真正想要持久保存的对象。
最佳答案
这个答案来晚了,但希望能帮助其他人。 是的。您创建了一个子上下文。在那里做任何你想做的事。如果 你想保留你的更改,保存子上下文 - 它不会保留数据。它通知父上下文更改,更改现在在您的主要上下文中。然后您可以在主上下文中执行保存。
let childContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
childContext.parentContext = mainContext
guard let myClass = NSEntityDescription.insertNewObjectForEntityForName("MyClass", inManagedObjectContext: childContext) as? MyClass else {
// something went wrong, handle it here
return
}
// do your thing here
让主上下文知道你想保留你的更改:
do {
try childContext.save() // does not persist anything, just lets know the parent that we are happy with the changes
} catch {
// handle error
}
当您不想保留您的更改时,您可以重置:
childContext.reset()
当您想在主上下文中保留更改时,您可以像往常一样:
do {
try mainContext.save()
} catch {
// handle error
}
关于ios - 摆脱临时保存的 managedObjectContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26842439/