1
votes

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?

1
As the error message said, you cannot use non-local object(aka the instance variable *error) here. It will cause memory leak, if you use this instance variable *error again somewhere in the code. As the instance variable *error is gonna be overwritten without being released if you use it somewhere else. - Eric Qian

1 Answers

2
votes

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.