Use NSManagedObject class without initWithEntity:?

走远了吗. 提交于 2019-11-27 16:20:25

问题


My problem is similar to: Problem creating NSManagedObject derived class

I have setup a NSManagedObject in Core Data and have a class for it. However, instead of creating an identical NSObject class, I'd like to use the NSManagedObject class, but I don't want to create the entity and save it. I just want to use it for an array, only when I need to save the object in Core Data do I want to use insertEntity:

Store *store = [[Store alloc] init];

It's giving me the following error: CoreData: error: Failed to call designated initializer on NSManagedObject class 'Store'

Is there a way to either subclass or somehow use the NSManagedObject class/properties to allocate objects I am just using temporarily for a table?

Thank you.


回答1:


Just use initWithEntity:insertIntoManagedObjectContext: and pass a nil context, then call insertObject: in your NSMAnagedObjectContext when you are ready:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyModelClass" inManagedObjectContext:myContext];
id object = [[MyModelClass alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];



回答2:


If you don't save the MOC, then you can simply delete the object before the save and it will never be persisted.

While Core Data is great for persisting, it is not required. In fact MOCs are often described as a scratch pad. You can generate objects and then throw them away.

An instance of NSManagedObjectContext represents a single “object space” or scratch pad in an application.

Another solution is to have a separate MOC for temporary objects and then either throw away the temp MOC or move the MOs into your persistent MOC.

So in this case you would - (void)insertObject:(NSManagedObject *)object on the "Persistent MOC" and then - (void)deleteObject:(NSManagedObject *)object on the "Temporary MOC".



来源:https://stackoverflow.com/questions/8139033/use-nsmanagedobject-class-without-initwithentity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!