I'm sure this must be a stupid question, but I've scoured the interwebbings and can't find the answer. Plenty of people talk about using the Generation Gap pattern, in which you have an NSManagedObject subclass that is generated from your model, and then subclass that to add transient properties and behaviours. The benefit of this is that if you change your persisted model, you can just generate your base files again without any danger of overwriting your own code.
I have a base CardMO object derived from NSManagedObject. I then subclass this to make my own Card object.
My question is, how do I create a Card object that is managed?
I tried:
Card* card = [NSEntityDescription insertNewObjectForEntityForName:@"CardMO" inManagedObjectContext:moc];
But this object isn't really a Card, and of course there's an exception when I go on to call a Card method on this object.
I've tried creating a Card with alloc / init (where init just calls [super init]), and then adding it to the managedObjectContext like this:
[moc insertObject:(CardMO*)card];
This gives me the cryptic error "Failed to call designated initializer on NSManagedObject class 'Card'"
I've tried modifying this by calling [NSEntityDescription insertNewObjectForEntityForName:@"CardMO" inManagedObjectContext:[AIStoreManager sharedAIStoreManager].managedObjectContext] instead of [super init]. In this case the object I get back is again a CardMO, and I can't call Card methods on it.
What should I be doing?
And (for bonus points :-) - after I've passed this hurdle, I need to create my other Card objects from XML, and then turn them into NSManagedObjects. I'm using code based on Apple's XMLReaderSAX - I hand this code a chunk of XML, and it gives me back an array of many Card objects. Can I later add these objects to my managed object context, or do I have to get into XMLReaderSAX and change how it creates those objects?
I'm writing an iPhone app on 3.0, but I assume this is the same for Core Data for 10.5.
Sussed it!
In the data model, the class name for the entity has to be that of the most derived class - Card in my case. The trouble then is that you have to remember to change the name to CardMO before generating any new files.
This must be why people use mogenerator.
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