- I have a vehicle entity in my data model.
- It has name, make, model, etc attributes.
- I've got a modal segue to the NewVehicleViewController which allows the user to enter entity information.
- I've passed the managedObjectContext to the NewVehicleViewController during this segue
Clicking 'Done', creates a new NSEntityDescription by calling the create+vehicle.m's method from within the NewVehicleViewController's IBAction method.
Vehicle *car = [Vehicle vehicleWithName:name inManagedObjectContext:self.context];
This method does the following:
+ (Vehicle *) vehicleWithName:(NSString *)name inManagedObjectContext:(NSManagedObjectContext *) context
{
Vehicle *vehicle = nil;
//check for duplicates
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Vehicle"];
request.predicate = [NSPredicate predicateWithFormat:@"name = %@", name];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error;
NSArray *matches = [context executeFetchRequest:request error:&error];
NSLog(@"Matches: %d", matches.count);
if(!matches || [matches count] >1){
//nil or more than 1
} else if ([matches count] == 0){
//not found
vehicle = [NSEntityDescription insertNewObjectForEntityForName:@"Vehicle" inManagedObjectContext:context];
vehicle.name = name;
}else{
vehicle = [matches lastObject];
NSLog(@"vehicle already exists with name: %@", name);
}
NSLog(@"Created vehicle with name: %@", vehicle.name);
return vehicle;
}
When the window closes, and I return back to my Table View controller, I can see the new element in there. (This table is linked to a fetch statement). Everything's all good.
Then about 4-6 seconds later, I get an exception thrown. The debug log at the bottom shows nothing, and it brings me to a Thread 8 view with a break on the first line.
libobjc.A.dylib`objc_exception_throw:
0x1780caa: pushl %ebp
0x1780cab: movl %esp, %ebp
0x1780cad: pushl %ebx
0x1780cae: pushl %edi
0x1780caf: pushl %esi
0x1780cb0: subl $2028, %esp
0x1780cb6: calll 0x01780cbb ; objc_exception_throw + 17
So my first question is, any idea what the problem is? Is this happening due to the NS Core Data's auto save that's happening some time later?
And my second question is, how could I have debugged this further to find out what the problem is?
Thanks!
Turns out, I renamed the entity in the model from Car to Vehicle. I propagated the changes through the code, but the simulator still had the app saved on it. The database inside the app had original Cars still stored in it, but now they are called Vehicles.
This was causing an exception to occur after a save.
I ended up delete the app from the simulator, and then running it again, and it worked.
Thanks!