如何处理临时NSManagedObject实例?

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

我需要创建 NSManagedObject 实例,与他们做一些东西,然后将它们或存储到sqlite db。问题是,我不能创建 NSManagedObject 的实例未连接到 NSManagedObjectContext ,这意味着我不得不清除决定我不需要我的db中的一些对象。

为了处理它,我使用同一个协调器创建了一个内存存储,我使用 assignObject: toPersistentStore。现在,如何确保这些临时对象不会获取数据,我从共同的两个存储上下文获取?或者,我必须为这样的任务创建单独的上下文吗?

UPD:

现在我正在考虑为内存存储单独创建上下文。如何将对象从一个上下文移动到另一个上下文?只是使用[上下文insertObject:]?它会工作正常在这个设置?

解决方案

如果我从对象图中插入一个对象,这是创建你的 NSManagedObject 实例没有相关联的 NSManagedObjectContext 。

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

然后当您要保存时:

[myMOC insertObject:unassociatedObject]; NSError * error = nil; if(![myMoc save:& error]){ //响应错误} 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.

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?

UPD:

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?

解决方案

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];

Then when you want to save it:

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

更多推荐

如何处理临时NSManagedObject实例?

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

发布评论

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

>www.elefans.com

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