Alex Rivera | Logout

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

Asked 2009-05-04T22:48:21.437
158

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

Edit
Report

1 Answer

1

Having an underscore not only makes it possible to resolve your ivars without resorting to using self.member syntax but it makes your code more readable since you know when a variable is an ivar (because of its underscore prefix) or a member argument (no underscore).

Example:

- (void) displayImage: (UIImage *) image {

    if (image != nil) {
        // Display the passed image...
        [_imageView setImage: image];
    } else {
        // fall back on the default image...
        [_imageView setImage: _image];
    }
}
answered 2012-04-19T05:13:58.197

Your Answer