views:

1133

answers:

3

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

+2  A: 

It doesn't really mean anything, it's just a convention some people use to differentiate member variables from local variables.

As for the error, it sounds like aMission has the wrong type. What it its declaration?

smorgan
It's common in IDE's with intellisense; it will make your member/module/class variables show at the top of the list. Another common previx is "m_"
STW
if it doesn't mean anything how can you switch back and forth between _missionName and missionName like in my example above?My declaration looks like:Mission *aMission = [[Mission alloc] init];aMission.missionName = @"a mission";
Buffernet
One is an instance variable and the other is a property. You can't access instance variables with syntax like aMission.missionName, because that syntax doesn't work with pointers.
Chuck
Also, note that you are trying to operate on a Mission object, but the interface you have posted with the missionName property is a MissionCell.
smorgan
+5  A: 

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;
Kelan
A: 

It's just a convention for readability, it doesn't do anything special to the compiler. You'll see people use it on private instance variables and method names. Apple actually recommends not using the underscore (if you're not being careful you could override something in your superclass), but you shouldn't feel bad about ignoring that advice. :)

Marc Charbonneau
From what I understand, Apple recommends against using the underscore prefix on method names (they reserve that for themselves as a convention for private methods), but they don't have any such recommendation about instance variable names.
Kelan