I am trying to update an existing record in a database using CoreData, but I am getting an exception when using the Managed Object accessor method.
Code excerpt:
NSManagedObjectContext *tmpManagedObjectContext = [self.fetchedResultsController managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:tmpManagedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"contact_id = %@", [dict objectForKey:@"contact_id"]];
[request setPredicate:predicate];
NSError *error = nil;
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"first_name",@"sync_status",nil]];
Contact *contact = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
contact.sync_status = @"Y";
error = nil;
if (![tmpManagedObjectContext save:&error]) {
NSLog(@"Error setting sync status on contact record - error: %@", [error localizedDescription]);
}
The line that is causing the error is:
contact.sync_status = @"Y";
Error is * Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[NSKnownKeysDictionary1 setSync_status:]: unrecognized selector sent to instance 0x8907fd0’
* First throw call stack:
Contact is a NSManagedObject class which I automatically generated in Xcode.
Is my approach incorrect here? I haven’t had any problems with retrieving or deleting records, but I am stumbling on how to update data.
Any guidance or help would be greatly appreciated. Thanks.
You’ve configured your fetch request to return dictionaries instead of managed objects. If you want to update the returned objects, you must ask for them in the fetch request – that is, use the default behaviour instead of what you are doing.
Remove these lines:
And you’ll be fine. The lines above are used if you only want to return certain properties in the fetch, but you want the whole object.