Objective-C – When to use ‘self’

Using self causes your class’ “setter” for this variable to be called, rather than changing the ivar directly.

self.mainViewController = aController;

is equivalent to:

[self setMainViewController:aController];

On the other hand:

mainViewController = aController;

just changes the mainViewController instance variable directly, skipping over any additional code that might be built into UIApplication’s setMainViewController method, such as releasing old objects, retaining new ones, updating internal variables and so on.

In the case where your accessing the frame, you’re still calling a setter method:

mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;

expands to:

[[mainViewController view] setFrame:[[UIScreen mainScreen] applicationFrame]];

Ideally, to future proof your code, you should also be using self.mainViewController (or [self mainViewController]) when retrieving this value too. In general, classes are much less likely to have important code in their “getter” methods than their “setters”, but it’s still possible that accessing directly could break something in a future version of Cocoa Touch.

Leave a Comment