James Fazio
James Fazio

Reputation: 6450

Objective C when to Alloc and Init Clarification

I am looking for some clarification on initializing variables in Objective C.

Say I have a method that returns an array.

-(NSMutableArray *) getArray
{
    NSMutableArray *arr = [[NSMutableArray alloc]init];  //line A

for(int i = 0; i < 10; i++)
{
    [arr addObject:@"word"];
}

return arr;
}

And then I call this method.

NSMutableArray *myArray = [[NSMutableArray alloc]init];  //line B
                myArray = [self getArray];

So should I be allocating memory in both lines A and B, neither, or in just A or just B? The alternative being simply

NSMutableArray *arr;      //replacing line A
NSMutableArray *myArray;  //replacing line B

Upvotes: 0

Views: 96

Answers (2)

fishinear
fishinear

Reputation: 6336

You should allocate memory in A, but in B. The alloc/init in A creates the object that the variable arr is refering to. You pass that object as the return value of method getArray.

In B, you simply want myArray to refer to the returned object, you don't want to have a new object. If you do:

NSMutableArray *myArray = [[NSMutableArray alloc]init];  //line B
                myArray = [self getArray];

the first line creates a new object and assigns that to myArray. The second line replaces that value of myArray immediately with another object that is returned from the method. Without ARC (automated reference counting), this will lead to a memory leak of the object created in the first line.

Upvotes: 1

Phillip Mills
Phillip Mills

Reputation: 31016

For any one array, you should be allocating its memory and initializing it once.

To start with, that means that your alternative at the end doesn't work. It's declaring that these two variables exist and will point to arrays but does nothing to create and assign them.

Line B creates and initializes an array just fine, but then immediately loses its only reference to it by assigning the result of getArray to the same variable. If you use ARC memory management, that's a bit wasteful; without ARC, it's a memory leak.

Line A also creates and initializes an array correctly and, as far as the code you've posted goes, that's the one that gets affected by whatever you do next to myArray.

(Remember that the things you declare as variables -- like NSMutableArray *arr -- can be thought of as names for the actual objects rather than objects themselves.)

Upvotes: 1

Related Questions