EXC_BAD_ACCESS KERN_INVALID_ADDRESS while accessing core data

928 views Asked by At

I've made a generic function in app delegate to access core data from anywhere in the app.

- (NSMutableArray *)createFetchRequestWithPredicate:(NSPredicate *)predicate inEntity:(NSString *)str_entity {

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:str_entity];
        request.predicate = predicate;
        [request setReturnsObjectsAsFaults:NO];
        NSMutableArray *arr_records = [[[NSMutableArray alloc] initWithArray:[[self managedObjectContext] executeFetchRequest:request error:nil]] mutableCopy];
        return arr_records;
}

Now most of the times this function works fine. But once in a hundred or so times it results in a crash with following log:

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000432b2b10

Can anybody sort out where the problem is.

1

There are 1 answers

8
Vinit Ingale On

I hope it is due to threading issue. As it is generic function and it can be called from anywhere in the app, use @synchronize(self) { } . Also add NSError parameter to executeFetchRequest method and handle error also.

- (NSMutableArray *)createFetchRequestWithPredicate:(NSPredicate *)predicate inEntity:(NSString *)str_entity {
   @synchronize(self) {

     NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:str_entity];
     request.predicate = predicate;
     [request setReturnsObjectsAsFaults:NO];
     NSError *error = nil;

     NSMutableArray *arr_records = [[[NSMutableArray alloc] initWithArray:[[self managedObjectContext] executeFetchRequest:request error:&error]] mutableCopy];

      if (!error) {
       return arr_records;
      } else 
        nil;
    }
}