views:

2044

answers:

1

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.

+5  A: 

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.

Jane Sales
To make the managed object from the parser, I had to get in to the Apple-derived code and change the object creation code to look like the above. It worked fine.
Jane Sales