zhuber
zhuber

Reputation: 5524

Understanding Objective-C method value passing

Lets say I have in viewDidLoad:

NSMutableArray *entries = [NSMutableArray array];
[self doSomethingWithArray:entries];

NSLog(@"%@", entries);

Then in method I have:

- (void)doSomethingWithArray:(NSMutableArray *)entries
{
    // create some custom data here, lets say - Something *something...
    [entries addObject:something];
}

How is it possible that entries (one at the top) now (after method is finished) contain object something, since object "something" is not added to property or instance variable, and nslog will log class "Something" ? And doSomethingWithArray doesn't return anything since its "void".

I have encountered this for first time and dunno if there is any name of this appearance ?

I have seen this for second time in some examples and really dunno how its done.

If anyone could explain this a bit whats happening here I would be very very grateful.

Thank you a lot.

Upvotes: 0

Views: 106

Answers (2)

Ratikanta Patra
Ratikanta Patra

Reputation: 1177

When you are adding the something object to the array, the array always retains it i.e it maintains copy of the Something object.

So NSLog prints the something.

Hope that helps.

Upvotes: 0

DrummerB
DrummerB

Reputation: 40211

Because Objective-C instances are passed by reference (as you can tell by the * pointer syntax). You basically pass the address of the array to the doSomethingWithArray: method. In that method you add something to the array referenced by that address. And of course once the method returns, your array will contain that new object.

Upvotes: 1

Related Questions