Consider this example:
NSMutableArray *aArray;
[Util doSomeMagic:aArray];
[aArray count];
- (void)doSomeMagic:(NSMutableArray *)aArray
{
if(aArray == NULL)
{
aArray = [[NSMutableArray alloc] init];
}
[aArray addObject:@"magic"];
[aArray addObject:@"magic2"];
}
The doSomeMagic: method will fill in the array. Inside doSomeMagic:, I can get the array count correctly, but outside the method, the array remains empty. How can I let the doSomeMagic: method change the content that is passed in?
Your
doSomeMagic:method needs to receive the array by reference, ensuring it modifies the object it receives:I’m guessing your
doSomeMagic:might look like this (which doesn’t work because it modifies a copy of the array for scope):EDIT: I see you’ve added your
doSomeMagic:code. You need to understand pass by reference here. Since you calldoSomeMagic:with a nil array (because you declaredaArraywithout setting it to point to anything afterwards), whendoSomeMagic:runs it assigns a new array to nil, and then the method returns with no visible effect. I suggest changing the code where you call it to:and your
doSomeMagic:method to:Keep in mind that since I am using the class
arrayon NSMutableArray, the array returned will be autoreleased after[aArray count];. The final code would look like this: