How to release a array which is created inside a for loop in Objective C?
I have created an array inside a for loop and I am not able to release it. It shows memory leaks. Here is my code :
for(int i = 0; i < [magArr count]; i++)
{
Magazine *magObj = [magArr objectAtIndex:i];
NSMutableArray *myArray = [data readEditions:[magObj.magazineID intValue]:0];//returns a array
}
[myArray release]; // memory leaks (retain count to -1)
If I use auto release also, it showing memory leak. How to s开发者_JS百科olve this leak?
If the array that is being returned from readEditions
is not autoreleased, it violates the Object ownership policy.
You should release the object inside the loop because it is being leaked after every iteration of the loop if readEditions
returns an object with a retain count > 0.
You should return an autoreleased object from readEditions
because the method name does not contain alloc
, new
or copy
.
Then, if you want, you can retain
the autoreleased object to keep it around.
Here's an example of how your loop would look like if readEditions
returned an autoreleased object:
for(int i = 0; i < [magArr count]; i++)
{
Magazine *magObj = [magArr objectAtIndex:i];
NSMutableArray *myArray = [[data readEditions:[magObj.magazineID intValue]:0] retain];
//do something with myArray...
[myArray release];
}
精彩评论