Search code examples
objective-cpropertiessetterivar

Setting and using ivars or passed parameters in setter functions


I know this sounds like a really silly and stupid question but is there any difference in using the target ivars or the passed parameters when making extended setter functions like in:


- (void)setText:(NSString)text {
    _text = text;
    self.label.text = text; // VS
    self.label.text = _text;
}

Is there any functionality or efficiency difference between the two assignments for self.label.text?


Solution

  • No, there is no difference between using the ivar and the passed parameter in your example.

    However, there is a difference if you use the accessor:

    // These are the same
    self.label.text = text;
    self.label.text = _text;
    
    // This will call the getter
    self.label.text = self.text
    

    As an illustration of the difference, consider if we had a custom (silly) getter:

    - (NSString *)text
    {
        return @"Hello";
    }
    

    In this case, the literal string @"Hello" would be returned regardless of the value of text.