How does an underscore in front of a variable in a cocoa objective-c class work?

Atma picture Atma · May 5, 2009 · Viewed 51.7k times · Source

I've seen in a few iPhone examples that attributes have used an underscore _ in front of the variable. Does anyone know what this means? Or how it works?

An interface file I'm using looks like:

@interface MissionCell : UITableViewCell {
    Mission *_mission;
    UILabel *_missionName;
}

@property (nonatomic, retain) UILabel *missionName;

- (Mission *)mission;

I'm not sure exactly what the above does but when I try to set the mission name like:

aMission.missionName = missionName;

I get the error:

request for member 'missionName' in something not a structure or union

Answer

Kelan picture Kelan · May 5, 2009

If you use the underscore prefix for your ivars (which is nothing more than a common convention, but a useful one), then you need to do 1 extra thing so the auto-generated accessor (for the property) knows which ivar to use. Specifically, in your implementation file, your synthesize should look like this:

@synthesize missionName = _missionName;

More generically, this is:

@synthesize propertyName = _ivarName;