I am trying to add external data into SQLite / update existing data using Core Data.
Basically, I am given a JSON from external web service and I am using following piece of code to find out whether I should add new or update existing object in DB.
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"name" inManagedObjectContext:context]];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"id = %@", [data valueForKey:@"key"]]];
NSArray *results = [context executeFetchRequest:fetch error:nil];
if (results.count == 1)
{
// update existing
}
else
{
// add new
}
The problem is: sometimes this code leads to an exception:
Thread 1: EXC_??? (11) (code=0, subcode=0x0)
The exception is raised in NSManagedObjectContext executeFetchRequest:error:
If I continue execution of my app everything seems ok.
Should I worry about this exception?
I mean it’s kind of annoying to have it but more important to know what is the cause and what are consequences of this exception?
Some additional detail (just in case it’s relevant):
- Code above gets executed multiple times in a loop (about 250 thousand times).
- Code runs on main thread (yeah, I know, but it’s kind of prototype).
- Context was created on main thread.
- External data is created in a background thread
[EDIT] Some more detail:
executeFetchRequest:errorreturns initialized array even when the exception was raised.- there is no error set when I provide
errorparameter toexecuteFetchRequest:error
That’s not safe.
You should check the return of the method to make sure you was handed an array back
Also CoreData seems to throw exceptions internally but handles them, so if you have an exception breakpoint set it will most likely get caught at random points from the CoreData stack – I’m saying this from past experience not sure if it’s documented anywhere but it is mentioned in this video Debugging Tips – Mike Hay