1

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. Commented Mar 4, 2013 at 3:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.