Search code examples
ioscore-datansfetchrequest

Using NSFetchRequest correctly


I am new to CoreData and trying to write a generic function to query information from the database. I face some problems.

I have set a private variable called NSError *error. My code looks like this:

@interface DatabaseHandler ()
{
    NSError * error;
}
@end

-(void)queryCoreDataModel:(NSString*)tableName sortBy:(NSArray *)sortArray{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:tableName];
    request.fetchLimit = 20;
    request.sortDescriptors = sortArray;
    [context executeFetchRequest:request error:&error];
}

It gives me this error: Passing address of non-local object to __autoreleasing parameter for write-back.

But when I do this:

-(void)queryCoreDataModel:(NSString*)tableName sortBy:(NSArray *)sortArray{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:tableName];
    request.fetchLimit = 20;
    request.sortDescriptors = sortArray;
    NSError *error;
    [context executeFetchRequest:request error:&error];
}

It gives me no error. Why is this so?


Solution

  • The error variable cannot be an instance variable as instance variables are not allowed to be autoreleasing. The error parameter is required to be autoreleasing to avoid a leak and that's why the local variable works.