views:

56

answers:

3

Hi there,

I am trying to understand the purpose of the synthesize directive with property name overriding. Say that I have an interface defined as follow:

@interface Dummy ... {
    UILabel *_dummyLabel;
}

@property (retain, nonatomic) UILabel *dummyLabel;

And in the implementation file, I have:

@synthesize dummyLabel = _dummyLabel;

From what i understand, "dummyLabel" is just an alias of the instance variable "_dummyLabel". Is there any difference between self._dummyLabel and self.dummyLabel?

+1  A: 

Yes. self._dummyLabel is undefined, however _dummyLabel is not.

You can only use dot syntax for synthesized properties.

self.dummyLabel  //works
self._dummyLabel //does not work
dummyLabel       //does not work
_dummyLabel      //works
Jacob Relkin
Thanks for the quick answer. Hm... okay, are [self.dummyLabel setText:@"..."] and [_dummyLabel setText:@"..."] doing the samething? If so, I don't see any big advantage of renaming _dummyLabel to dummyLabel.
Thomas
@Thomas, You got it.
Jacob Relkin
+1  A: 

Your understanding is incorrect. dummyLabel is the name of the property, and is not an alias for the instance variable - the instance variable is only called _dummyLabel. So the following holds for an instance of Dummy called myObject:

  • [myObject dummyLabel] works
  • myObject.dummyLabel works
  • [myObject _dummyLabel] fails
  • myObject._dummyLabel fails
  • myObject->dummyLabel fails
  • myObject->_dummyLabel depends on the visibility of the ivar (@public, @private, @protected)
  • [myObject valueForKey: @"dummyLabel"] works
  • [myObject valueForKey: @"_dummyLabel"] depends on the implementation of +accessInstanceVariablesDirectly (i.e. it will work in the default case where +accessInstanceVariablesDirectly returns YES).
Graham Lee
A: 

I don't see any big advantage of renaming _dummyLabel to dummyLabel

In some ObjC runtimes you have a hard time making instance variables invisible to users of the class. For them sticking some prefix (or suffix) on your instance variables can make it clear (or more clear) that you don't want anyone messing with your variables. However you don't want that gunk on your public functions. This lets you get it off.

It could also be useful if you need to maintain an old interface with one set of names at the same time as a new set of APIs with a new set of names (setLastname vs. setSurname).

Stripes