Search code examples
ioscore-datansmanagedobjectcontextnsfetchrequest

Not able to handle executeFetchRequest error


My fetch request works fine and I get my fetched objects without any problems. What I want to do, is handle the error in case the entity doesn't exist. The problem is, I can't handle the error because the app crashes when I call executeFetechRequest: error: without any warnings.

My fetch looks like:

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Info" inManagedObjectContext:context];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"infoID" ascending:YES]];
[request setReturnsObjectsAsFaults:NO];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"infoID like %@",[a substringFromIndex:13]];
request.predicate = predicate;
request.fetchBatchSize = 1;

NSError *error = nil;

NSArray *results = [context executeFetchRequest:request error:&error];

if (error == nil) {
    ...
}
else {
    //handle error
}

As I said, there's no problem as long as the entity exists, but I want to handle the error if it doesn't exist. Any idea? Cheers


Solution

  • You could ask the model if such entity is present:

        NSArray *entities = managedObjectModel.entities;
        BOOL canExecute=NO;
        for(NSEntityDescription *ed in entities) {
           // check if entity name is equal to the one you are looking for
           if(found) {
              canExecute=YES;
              break;
           }
        }
    
       if(canExecute) {
         // execute your request and all the rest...
       } else {
         NSLog(@"Entity description not found");
       }
    

    if doesn't exist you don't execute the fetch reuest