mineschan
mineschan

Reputation: 473

How to release the NSMutableArray about to return but NOT the objects inside?

As the following code, I pass objects to make some data reset in this method, contained by a NSMutableArray. All good, code works.

But when I use Xcode Build and Analyze, it warns me "Potential leak" for the *newObjs. If I add autorelease to it. I will lose my objects inside for future usage.

What should I do??

-(NSMutableArray*)resetNotGivenDrugs:(NSMutableArray *)drugObjs{

NSMutableArray *newObjs = [[NSMutableArray alloc]init]; 
//i can't release this though i have objects still need to be use inside

for(Drug *drug in drugObjs){

    // some process to modify the Drug object that i don't want to be release

    [newObjs addObject:drug];
}

return newObjs;
}

Upvotes: 0

Views: 93

Answers (2)

hypercrypt
hypercrypt

Reputation: 15376

Why are you returning a new array? If you are just changing properties if drug then they will be reflected in drugObjs and thus [drugObjs isEqual:newObjs] is true.

On the memory issue, you should autorelease newObjs. The caller should retain it if it needs to stay around past the end of the calling function.

Upvotes: 1

jrturton
jrturton

Reputation: 119242

You should return [newObjs autorelease] rather than newObjs as the method suggests that an autoreleased object will be returned (doesn't contain new or init etc in the title). You won't lose references to the objects inside until the autorelease pool is drained, which won't be (usually) until the end of the run loop.

If you need to keep hold of the returned array, retain it in the calling method, but as I say the array and contents won't be released until you have finished executing. That's the point of autorelease.

Upvotes: 1

Related Questions