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
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
getArrayto 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.)