开发者

Can I create manually an instance of an Core Data Entity class for temporary usage?

I have an custom class for an Core Data entity, called 'Friends'. As I am parsing an XML File, I need to create temporary instances to hold temporary data, without using Core Data at this point. So there are two options:

A) create an NSMutableDictionary to hold the temporary data while parsing an "object" from the XML.

B) use the class of the entity to store temporary data while parsing. I would prefer that, because it is more clear and more DRY for me, since the data structure is declared in there already and I wouldn't have to duplicate the whole data model of that entity in an NSMutableDictionary.

But B has a problem: By default, all the properties are @dynamic, and as far as I know, Core Data takes care of creating the implementations at runtime. So I can't just use the properties there. So this raises the qu开发者_如何学运维estion if it's worth the effort and even possible to modify that class in such a way that it can be used without Core Data as a temporary data container object, i.e. by creating instance variables. Of course, if I had to create an dictionary in there to hold the temporary data, that would make no sense at all, and I would just go with A.


UPDATE: It sounds like you can use a nil context (see Adam's answer below)

Unfortunately, the only way to instantiate a managed object subclass is by inserting it into a context.

Using a mutable dictionary (NSMutableDictionary) is the best approach since you can use setValuesForKeysWithDictionary: to populate the new managed object with a single method call.

Another approach would be to insert the managed object and then delete it if you determine that it is not new. If you haven't saved, the object will never even have been written to the persistent store.
Note: this assumes that you determine if the object is new before adding its unique ID or you exclude the temporary objects (with an attribute or filtering out using a collection of them) when fetching the unique ID(s) so that you are only checking objects that existed previously.


Disagreeing with gerry3, Apple's docs imply the opposite. You simply have to call the designated initializer with a nil context:

- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context

... If context is not nil, this method invokes [context insertObject:self] (which causes awakeFromInsert to be invoked).

This seems to work (I'm using temp NSManagedObjects at the moment - although I might be doing it wrong).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜