objc_exception_throw When Returning NSManagedObject
- by spamguy
I have a method dedicated to finding an NSManagedObject ('company') using a supplied NSString and, if it's not found, creating a new one and returning it. As far as I know it's fully inited and the method works perfectly. That is, until the line after the return statement, when the app crashes with an objc_exception_throw. I googled this and couldn't find what causes it, only how to use it in breakpoint debugging.
What's wrong with this method, and why is it throwing specifically this exception?
- (NSManagedObject*) getCompanyObject:(NSString*)theCompany
{
NSError *error = nil;
NSManagedObjectContext *moc = [[self delegate] managedObjectContext];
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:moc];
[fetch setEntity:entityDescription];
// object to be returned
NSManagedObject *companyObject = [[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:moc];
// set predicate (company name)
NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name = \"%@\"", theCompany]];
[fetch setPredicate:pred];
NSArray *response = [moc executeFetchRequest:fetch error:&error];
if ([response count] == 0) // empty resultset --> no companies with this name
{
[companyObject setValue:theCompany forKey:@"name"];
NSLog(@"%@ not found. Adding.", theCompany);
}
else
[companyObject setValue:[[response objectAtIndex:0] valueForKey:@"name"]];
return companyObject;
}