如何安全删除未保存的托管对象?

发布于 2024-12-04 05:57:35 字数 454 浏览 0 评论 0原文

我的应用程序为“文本文章”提供了某种编辑器功能。我的编辑器有两种模式。当编辑器加载时,如果尚未通过初始化程序传入托管对象,我将创建一个托管对象。当用户取消新编辑时,我从上下文中删除该对象。但是,有时,我会收到有关对象未插入上下文的错误,有时则不会。那么,以下代码是检查托管对象实例是否已插入上下文的好方法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

各自安好 2024-12-11 05:57:35

如果可能,应始终使用相同的托管对象上下文,而不是它的各种实例。如果您有多个视图控制器,则应该传递相同的上下文作为引用。比较上下文并不能告诉您有关实体实例是否存在的任何信息。

以通常的方式初始化对象后,

myEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" 
   inManagedObjectContext:self.managedObjectContext];

您可以检查它是否存在并使用简单的方法删除它

if (myEntity) { 
   [self.managedObjectContext deleteObject:myEntity];
}

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

myEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" 
   inManagedObjectContext:self.managedObjectContext];

you can check if it exists and delete it with a simple

if (myEntity) { 
   [self.managedObjectContext deleteObject:myEntity];
}
情丝乱 2024-12-11 05:57:35

就我而言,我意识到应该在创建托管对象的初始实例后保存上下文。由于我仍然有参考它,所以我后来可以删除它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文