Why put underscore “_” before variable names in Objective C [duplicate]

The underscores are often used to show that the variables are instance variables. It is not really necessary, as ivars can have the same name as their properties and their accessors.

Example:

@interface MyClass : NSObject {
    NSString *_myIVar;                  // can be omitted, see rest of text
}
// accessors, first one is getter, second one is setter
- (NSString *) myIVar;                  // can be omitted, see rest of text
- (void) setMyIVar: (NSString *) value; // can be omitted, see rest of text

// other methods

@property (nonatomic, copy) NSString *myIVar;

@end

Now, instead of declaring and coding the accessors myIVar and setMyIVar: yourself, you can let the compiler do that. In newer versions, you don’t even have to declare myIVar in the interface. You just declare the property and let the compiler synthesize the rest for you. In the .m file, you do:

@implementation MyClass
@synthesize myIVar; // generates methods myIVar and setMyIVar: for you, 
                    // with proper code.
                    // also generates the instance variable myIVar

// etc...

@end

Be sure to finalize the string:

- (void) dealloc {
    [myIVar release]; 
    [super dealloc];
}

FWIW, if you want to do more than the default implementation of the getter or setter do, you can still code one or both of them yourself, but then you’ll have to take care of memory management too. In that case, the compiler will not generate that particular accessor anymore (but if only one is done manually, the other will still be generated).

You access the properties as

myString = self.myIVar;

or, from another class:

theString = otherClass.myIVar;

and

otherClass.myIVar = @"Hello, world!";

In MyClass, if you omit self., you get the bare ivar. This should generally only be used in the initializers and in dealloc.

Leave a Comment