I have an application that uses Core Data. I have two data models in the project and I create the ManagedObjectContext by merging the two models. Here the code where I do that:
- (NSManagedObjectModel *)managedObjectModel {
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
NSURL* entityURL = [[NSBundle mainBundle] URLForResource:@"User_data" withExtension:@"momd"];
NSManagedObjectModel* entityModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:entityURL];
NSURL* whoURL = [[NSBundle mainBundle] URLForResource:@"WHO_data" withExtension:@"momd"];
NSManagedObjectModel* whoModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:whoURL];
NSArray* models = [NSArray arrayWithObjects:entityModel, whoModel, nil];
__managedObjectModel = [NSManagedObjectModel modelByMergingModels:models];
return __managedObjectModel;
}
None of the attributes in my entities are optional and my app crashes when I try to save my managedObjectContext. I believe this is because some of the attributes are not being set. I have overridden awakeFromInsert: for the parent entity:
- (void) awakeFromInsert
{
[super awakeFromInsert];
NSString* userCFUUID = [[NSUserDefaults standardUserDefaults]objectForKey:@"device_identifier"];
if ( userCFUUID ) {
[self cfuuid:userCFUUID];
} else {
[NSException raise:NSInvalidArgumentException format:@"Entry: awakeFromInsert: cannot find CFUUID"];
}
[self setCreationDate:[NSDate date]]; // the time since Jan 1st 1970 in seconds
[self setEventDate:[NSDate date]];
}
But awakeFromInsert: is never called. I’ve set a breakpoint and stepped through from the statement where I create the NSManagedObject:
LengthEntry *length1 = [NSEntityDescription insertNewObjectForEntityForName:@"LengthEntry" inManagedObjectContext:moc];
Additional fact that may or may not be relavent:
After creating the datamodel containing the problem entity, I used the Xcode feature to automatically create the classes. I then realised that since I had not specified to do otherwise in the model, xcode named the classes in the plural sense (because that’s what I had called them in the model). So, I ended up with “Entries.h” instead of “Entry.h”. I went back and manually changed all the classes and specified in the model the name of the classes.
So, I need to figure out why awakeFromInsert is never called.
Out of desperation, I deleted the datamodel and the NSManagedObject classes. I then recreated the model and the classes.
Now, it works. Something screwy must have happened when I manually changed the names of the classes.