Arpit Parekh Arpit Parekh - 3 months ago 19
iOS Question

NSMutableArray: Memory management while calling methods

In my iOS app, I am using a NSMutableArray, named imageMArray. I have set its getter and setter properties and instantiated it.

In viewDidLoad:

imageMArray=[[NSMutableArray alloc] initWithArray:CategoryImages];
imageMArray=[self shuffleOnlyArray:imageMArray];


In ShuffleOnlyArray Method:

NSMutableArray *destArray1 = [[NSMutableArray alloc] initWithCapacity: [sourceArray count]] ;
return destArray1;


In shuffle Method:

imageMArray=[[self shuffleOnlyArray:imageMArray] retain];


There appears to be a memory leak in the Shuffle method.

Should I release imageMArray or set it to nil? If it should be released, should it be autoreleased?

Answer
imageMArray=[[NSMutableArray alloc] initWithArray:CategoryImages];

In the above statement, you have a memoryleak. Instead you can have like as follows.

imageMArray = [NSMutableArray arrayWithArray:CategoryImages];

In ShuffleOnlyArray Method, return the autoreleased object.

NSMutableArray *destArray1 = [[NSMutableArray alloc] initWithCapacity: [sourceArray count]] ;
return [destArray1 autorelease];

But after you get it, retain (take the ownership) the array object.

imageMArray=[[self shuffleOnlyArray:imageMArray] retain];

Edit

In shuffle method, do as follows:

NSMutableArray *imageMArray1 = [imageMArray mutableCopy];
if( imageMArray )
{
   [imageMArray release];
}
imageMArray=[[self shuffleOnlyArray:imageMArray1] retain];
[imageMArray1 release];

Edit 2: One more solution:

Use the category to shuffle as mentioned in the SO link

No need of creating new and releasing the arrays.

Comments