I have a Core Data model where I have an entity A, which is an abstract. Entities B, C, and D inherit from entity A. There are several properties defined in entity A which are used by B, C, and D.
I would like to leverage this inheritance in my model code. In addition to properties, I am wondering if I can add methods to entity A, which are implemented in it's sub-entities.
For example:
executeFetchRequest:
to retrieve all instances of BI have tried this, but when calling the method, I receive:
[NSManagedObject methodName:]: unrecognized selector sent to instance
I presume this is because the objects returned by executeFetchRequest:
are proxy objects of some sort.
Is there any way to leverage inheritance using subclassed NSManagedObjects?
I would really like to be able to do this, otherwise my model code would be responsible for determining what type of NSManagedObject it's dealing with and perform special logic according to the type, which is undesirable.
Any help is appreciated, thanks in advance.
From the Xcode menu bar, choose Editor > Create NSManagedObject Subclass. Select your data model, then the appropriate entity, and choose where to save the files. Xcode places both a class and a properties file into your project.
To implement a Transformable attribute, configure it by setting its type to Transformable and specifying the transformer and custom class name in Data Model Inspector, then register a transformer with code before an app loads its Core Data stack.
In some respects, an NSManagedObject acts like a dictionary—it's a generic container object that provides efficient storage for the properties defined by its associated NSEntityDescription instance.
Fetched Properties in Core Data are properties that return an array value from a predicate. A fetched property predicate is a Core Data query that evaluates to an array of results.
It should work. The objects returned by executeFetchRequest:
are real instances of NSManagedObject
s (or subclasses thereof.)
The steps to use custom classes in CoreData are as follows. Say you have entities A and B, where B inherits from A.
Then you need two custom classes as
@interface A:NSManagedObject{
}
-(void)someMethod:(NSString*)a;
@end;
@interface B:A{
}
-(void)someMethod:(NSString*)a;
@end;
Then set them in the XCode data modeler as shown:
This way, the CoreData automatically assigns the correct class to the NSManagedObject
when it is fetched from the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With