如何处理临时 NSManagedObject 实例?

编程入门 行业动态 更新时间:2024-10-27 07:25:38
本文介绍了如何处理临时 NSManagedObject 实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要创建 NSManagedObject 实例,用它们做一些事情,然后将它们丢弃或存储到 sqlite 数据库.问题是,我无法创建未连接到 NSManagedObjectContext 的 NSManagedObject 实例,这意味着在我决定不需要其中的某些对象后,我必须以某种方式进行清理我的数据库

I need to create NSManagedObject instances, do some stuff with them and then trash them or store to sqlite db. The problem is, I cannot create instances of NSManagedObject unconnected to NSManagedObjectContext and this means I have to clear up somehow after I decide that I don't need some of the objects in my db.

为了解决这个问题,我使用相同的协调器创建了一个内存存储,并使用 assignObject:toPersistentStore 将临时对象放置在那里. 现在,我如何确保这些临时对象对象没有访问数据,我从两个存储上下文的公共获取数据?还是我必须为这样的任务创建单独的上下文?

To deal with it, I have created an in-memory store using the same coordinator and I'm placing temporary objects there by using assignObject:toPersistentStore. Now, how do I ensure that these temporary objects don't get to the data, which I fetch from the common to both stores context? Or do I have to create separate contexts for such a task?

现在我正在考虑为内存存储创建单独的上下文.如何将对象从一个上下文移动到另一个上下文?只使用 [context insertObject:]?在这种设置下它会正常工作吗?如果我从对象图中插入一个对象,整个图是否也会插入上下文中?

Now I'm thinking about making separate context for in-memory store. How do I move objects from one context to another? Just using [context insertObject:]? Will it work OK in this setup? If I insert one object from the graph of objects, does the whole graph also get inserted into context?

推荐答案

注意:这个答案非常.查看完整历史记录的评论.我的建议已经改变,我不再建议使用未关联的 NSManagedObject 实例.我目前的建议是使用临时子 NSManagedObjectContext 实例.

NOTE: This answer is very old. See comments for full history. My recommendation has since changed and I no longer recommend using unassociated NSManagedObject instances. My current recommendation is to use temporary child NSManagedObjectContext instances.

原答案

最简单的方法是创建没有关联的 NSManagedObjectContext 的 NSManagedObject 实例.

The easiest way to do this is to create your NSManagedObject instances without an associated NSManagedObjectContext.

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:myMOC]; NSManagedObject *unassociatedObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];

然后当你想保存它时:

[myMOC insertObject:unassociatedObject]; NSError *error = nil; if (![myMoc save:&error]) { //Respond to the error }

更多推荐

如何处理临时 NSManagedObject 实例?

本文发布于:2023-11-25 14:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何处理   实例   NSManagedObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!