简体   繁体   中英

Can I add properties to subclass of subclass of NSManagedObject?

I have a class Base : NSManagedObject generated by core data, and in order to add some methods to this entity, I subclass it with Derived : Base . Now, I want to add a property (which is not in Base class) to Derived class. But when I try to access the setter of the added property, it throws an exception:

caught "NSInvalidArgumentException", "-[Base setAddedProperty:]: unrecognized selector sent to instance 0x7fdcc31b36d0"

Could anyone help?

EDIT: It seems that subclass of subclass of NSManagedObject cannot have its own methods because I just added a method to Derived and got the similar exception. Does that mean category is the only way to add methods to subclass of NSManagedObject?

EDIT: I changed the "Class" of entities in configurations to Derived and everything is working now. All those newly added properties can be accessed and customized methods can be invoked. Why? and is this a good practice?

EDIT: It seems the above descriptions are misunderstood. I intend to subclass the entity classes generated by core data in order to provide customized methods and properties, not to create child entities. Therefore, Derived is not an entity in data model.

You also should specify inheritance in xcdatamodel . Check fields: Name, Class, Parent Entity in xcdatamodel. Derived : Base isn't enough for NSManagedObject subclasses.

You need to select parent sheep (also try to set abstract entity for you Base) 查看这张图片,您将看到我对复选框的意思

I got this problem fixed.

In my .xcdatamodeld file, I mapped Base entity to Base class. In my codes, I create an instance by:

Derived* pointer = [Derived MR_createEntity];

This method invokes NSEntityDescriptor insertNewObjectForEntityForName:inManagedObjectContext for me. However, this method will return an instance of Base instead of Derived despite the pointer is of type Derived* , which should be an syntax error if in compilation.

Therefore, in order to make my methods in Derived valid, I need to manually change the mapping from Base to Derived .

EDIT: After writing this answer, I found an awesome tool mogenerator , which makes use of exactly the same idea as I described above and is really convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM