Reputation: 59
I know this has been asked before from different angles.
However, I did not yet see a straight answer how are explicit objects passed in objective-c. After a month of experience coding in objective c (coming from Java), I see that objects are passed by value.
Is that true?
In my code, I had a NSArray of objects of type Person. I took one of the objects from the NSArray, edited it and saw the values of any of the objects in NSArray not affected until I called replaceObjectAtIndex: method. To my surprise, this scenario showed me that explicit objects in Objective C are passed by value.
Upvotes: 1
Views: 459
Reputation: 81878
There was some kind of error in your test.
NSMutableString *string = [@"foo" mutableCopy];
NSArray *array = [NSArray arrayWithObject:string];
[string appendString:@"bar"];
NSLog(@"%@", array);
> [...] (
> foobar
> )
In Objective-C all objects are always referenced by a pointer.
Upvotes: 0
Reputation: 49386
Everything is passed by value in C, it's just that some of these values are pointers. Passing a pointer allows you to just pass a "signpost" to the target object, rather than the entire object itself. You manipulate the object through by following the pointers; anyone holding a pointer to the same object will see the changes made to it by any other code.
All Objective C objects are handled via pointers, so you should have seen the changes in your array example. For example,
NSArray *myArray = ...;
id element = [myArray objectAtIndex:n];
element.foo = @"Bar";
// [[myArray objectAtIndex:n] foo] is now "Bar";
What was your test code?
Upvotes: 0
Reputation: 100652
Objects in Objective-C are always passed by reference. In terms of how it interfaces with C, you're actually pointers to object by value but it's not worth splitting hairs.
Although there are two types of object literal in Objective-C, strings and blocks, and the latter of those is permitted to live on the stack rather than the heap, it is still handled by reference.
The test you performed must have been flawed in some way.
Upvotes: 2