-5

Look a setter like:

- (void)setCount:(NSNumber *)newCount {
    [newCount retain];
    [_count release];
    // Make the new assignment.
    _count = newCount;
}

If I call [self setCount:anNSNumber], the effect will occur (_count will be released, anNSNumber will be retained, ... as you know). But I know that in Obj-C pass by value is default. So, why that happend ?

Proton
  • 1,335
  • 1
  • 10
  • 16

2 Answers2

2

The parameter is passed by value. In this case the parameter is a pointer. The pointer, not the object, is passed by value.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

You are correct in saying the Objective-C uses pass-by-value; it is not simply the default but the only parameter passing mechanism supported. Objective-C++ supports C++ pass-by-reference as well.

In your expression [self setCount:anNSNumber] the value in the variable anNSNumber is passed to setCount. However that value is a reference of type NSNumber *, and that reference may be used to modify the object that is referenced.

The value that is passed for a parameter is used to initialise a local variable in the callee, and you can modify the value in that variable without any effect on the caller - this is the definition of call-by-value. So for example you could add to your setCount:

newCount = [NSNumber numberWithInteger:42];

and that would have no effect on the caller.

CRD
  • 52,522
  • 5
  • 70
  • 86