When to use self.myInstanceVariable and when to use _myInstanceVariable

Here’s a question I’ve had a few times so here are some simple rules. But, first a quick explanation.

self.myTitle means you’re accessing an instance variable that has been created using an @property such as:

@property (nonatomic, copy) NSString *myTitle;

Unless you’re doing something special (see an earlier post) what @property does is create getters / setters and an instance variable. Xcode prefixes the instance variable with an underscore.

Note that if you needed this to be differently named you would need to use @synthesize to manually set it however, you need a very good reason. By auto-generating instance variables with a leading underscore (now the convention for instance variable naming), Xcode makes @synthesize unnecessary.

So, if you don’t have any requirements for getters/setters (and have therefore not used @property) then you don’t have the option of using self.myTitle. You would simply access it using:

myTitle = @”some title”;

Typically you would do this when you just want to create a local variable.

However, if you are using an @property then you would access this instance variable using getters:

someLabel.text = self.myTitle;

If you had to access the instance variable directly then you would use the underscore prefix to access it:

someLabel.text = _myTitle;

However, you need to have a good reason to use an instance variable this way. An example would be in a dealloc method when you don’t know the state of your object and so getters/setters would work in unknown ways. However, with the introduction of ARC much of the code in books and on the internet with the dealloc method becomes defunct.

More info here:

http://useyourloaf.com/blog/2011/02/08/understanding-your-objective-c-self.html

and here:

http://stackoverflow.com/questions/822487/how-does-an-underscore-in-front-of-a-variable-in-a-cocoa-objective-c-class-work

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>