1

If I have an NSMutableArray or NSMutableDictionary and pass it to a method a la:

-(void)addToThisArray:(NSMutableArray *)theMutableArray
{
    [theMutableArray addObject:@"test"];
}

and call it like:

 NSMutableArray *theMutableArrayToPass = [[NSMutableArray alloc] init];
 [theMutableArrayToPass addObject:@"2"];
 [self addToThisArray:theMutableArrayToPass];

Is this a valid way to alter an NSMutableArray or NSMutableDictionary? I, of course, would do much more to the array/dictionary than this example, but I am used to Perl, and we pass by reference all the time.

jscs
  • 63,694
  • 13
  • 151
  • 195
Jann
  • 2,214
  • 3
  • 28
  • 45

1 Answers1

7

Yes, objective-c is also always pass by reference for objects.

Since this answer was written, there is now an exception though it is an implementation detail and doesn't change the practical details of the claim.

Tagged pointers are technically pass by value because the reference is really the data. They are also, by definition, immutable which is why this is an implementation detail that has not practical ramifications.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • Fantastic. I have a memory leak issue and was trying to track it down. I just wanted to make sure when I did this that I was not copying the entire array/dict and adding to it -- thus somehow doubling the memory it was not using. Thanks! ARGHHH! I cannot accept the answer for 11 more minutes. I will do so when stackoverflow allows me to. Again, thanks! – Jann Jul 10 '11 at 19:07
  • Do a search for "bbum heapshot analysis" and read the article I wrote about using Heapshot analysis to track down memory accretion. It'll likely nail your memory growth issue rather quickly. Best of luck! – bbum Jul 10 '11 at 20:37
  • Oh my gosh! I read your article which lead me to thinking about autorelease pools. So, I stuck it inside a `NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];` `[pool release]` and it went from 1.5G to 29MB! Thanks for leading me in a direction that helped me figure it out. I *hate* scope-related autorelease errors. (even when they are my own -- and I should've known!) +2 on this one. One for helping me with the byRef question...and another by leading me to an answer that had me scratching my head all night! – Jann Jul 10 '11 at 21:48
  • Awesome. Glad to have helped! – bbum Jul 10 '11 at 23:53
  • @bbum Why are there so many contrary answers? [like this one](http://stackoverflow.com/a/1344573/1803879), or [this one](http://stackoverflow.com/a/11737592/1803879), or perhaps [this one](http://stackoverflow.com/a/7689460/1803879) – Tom Howard Oct 18 '16 at 12:16
  • @TomHoward Because people are confused. In at least two of those answers, the objects are still being passed by reference, **but** the answer is actually passing the **reference** *by reference*. I.e. `NSString **` as an argument is "pass reference by reference" and not "pass object by reference". – bbum Oct 18 '16 at 21:44