gpt4 book ai didi

ios - 摆脱临时保存的 managedObjectContext

转载 作者:行者123 更新时间:2023-11-28 10:02:07 27 4
gpt4 key购买 nike

如何管理临时保存的 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/

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