开发者

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{

NSMu开发者_开发技巧tableArray *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;
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜