NSManagedObjectContext

NSManagedObjectContext

本文介绍了如何处理临时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实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:34