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;
}
You should return
[newObjs autorelease]rather thannewObjsas 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,
retainit 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 ofautorelease.