ref:
http://stackoverflow.com/questions/2892520/passing-arguments-by-value-or-by-reference-in-objective-c
Jared P is wrong, objective-C only support passing parameters by value. The problem here has probably been fixed already (Since this question is more than a year old) but I need to clarify some things regarding arguments and Objective-C.
Objective-C is a strict superset of C which means that everything C does, Obj-C does it too.
By having a quick look at Wikipedia, you can see that Function parameters are always passed by value
Objective-C is no different. What’s happening here is that whenever we are passing an object to a function (In this case a UILabel *), we pass the value contained at the pointer’s address.
Whatever you do, it will always be the value of what you are passing. If you want to pass the value of the reference you would have to pass it a **object (Like often seen when passing NSError).
This is the same thing with scalars, they are passed by value, hence you can modify the value of the variable you received in your method and that won’t change the value of the original variable that you passed to the function.
Here’s an example to ease the understanding:
1 2 3 4 5 6 7 8 9 10 11 |
- (void)parentFunction { int i = 0; [self modifyValueOfPassedArgument:i]; //i == 0 still! } - (void)modifyValueOfPassedArgument:(NSInteger)j { //j == 0! but j is a copied variable. It is _NOT_ i j = 23; //j now == 23, but this hasn't changed the value of i. } |
If you wanted to be able to modify i, you would have to pass the value of the reference by doing the following:
1 2 3 4 5 6 7 8 9 10 11 |
- (void)parentFunction { int i = 0; //Stack allocated. Kept it that way for sake of simplicity [self modifyValueOfPassedReference:&i]; //i == 23! } - (void)modifyValueOfPassedReference:(NSInteger *)j { //j == 0, and this points to i! We can modify i from here. *j = 23; //j now == 23, and i also == 23! } |
ref:
http://stackoverflow.com/questions/22213197/is-objective-c-pass-by-value-or-pass-by-reference
C does not support pass-by-reference and Objective-C, being a strict superset of C doesn’t either.
In C (and Objective-C) you can simulate pass-by-reference by passing a pointer, but it’s important to remember that you’re still technically passing a value, which happens to be a the value of a pointer.
So, in Objective-C (and C, for the matter) there is no concept of reference as intended in other languages (such as C++ or Java).
This can be confusing, so let me try to be clearer (I’ll use plain C, but – again – it doesn’t change in Objective-C)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
void increment(int *x) { *x++; } int i = 42; increment(&i); // <--- this is NOT pass-by-reference. // we're passing the value of a pointer to i On the other hand in C++ we could do void increment(int &x) { x++; } int i = 41; increment(i); // <--- this IS pass-by-reference // doesn't compile in C (nor in Objective-C) |