如何安全删除未保存的托管对象?
我的应用程序为“文本文章”提供了某种编辑器功能。我的编辑器有两种模式。当编辑器加载时,如果尚未通过初始化程序传入托管对象,我将创建一个托管对象。当用户取消新编辑时,我从上下文中删除该对象。但是,有时,我会收到有关对象未插入上下文的错误,有时则不会。那么,以下代码是检查托管对象实例是否已插入上下文的好方法吗?
if ([[self.workingManagedObjectInstance managedObjectContext] isEqual:self.managedObjectContext]){
}
我的理论是,如果 [self.workingManagedObjectInstance ManagedObjectContext]
为 nil
,则它尚未插入,也不会是“isEqual
”。这是检查我们没有删除尚未插入的对象的有效方法吗?
My app offers some sort of editor functionality for "text articles". My editor has two modes. When the editor loads, I create a managed object if it hasn't been passed in through the initializer. When the user cancels a new edit, I delete the object from the context. However, sometimes,I get an error about the object not being inserted into the context, and sometimes I don't. So, is the following code a good approach to check if a managed object instance was inserted into a context?
if ([[self.workingManagedObjectInstance managedObjectContext] isEqual:self.managedObjectContext]){
}
My theory is that if [self.workingManagedObjectInstance managedObjectContext]
is nil
, then it hasn't been inserted and will not be "isEqual
". Is that a valid way to check that we're not deleting an object that wasn't inserted yet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可能,应始终使用相同的托管对象上下文,而不是它的各种实例。如果您有多个视图控制器,则应该传递相同的上下文作为引用。比较上下文并不能告诉您有关实体实例是否存在的任何信息。
以通常的方式初始化对象后,
您可以检查它是否存在并使用简单的方法删除它
If possible should always use the same managed object context, not various instances of it. If you have more than one view controller, you should pass the same context as a reference. Comparing the context does not tell you anything about the existence of an entity instance.
After you initialize the object in the usual way
you can check if it exists and delete it with a simple
就我而言,我意识到应该在创建托管对象的初始实例后保存上下文。由于我仍然有参考它,所以我后来可以删除它。
In my case, I realized that I should be saving my context after creating the initial instance of the managed object. Since I still had a reference to it, I was able to delete it later.