Objective-C - When to Use 'self'

This is unmodified code from the Apple Utility Aplication template:

- (void)applicationDidFinishLaunching:(UIApplication *)application { MainViewController *aController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil]; self.mainViewController = aController; [aController release]; mainViewController.view.frame = [UIScreen mainScreen].applicationFrame; [window addSubview:[mainViewController view]]; [window makeKeyAndVisible]; } 

When mainViewController is assigned to aController , the self keyword is specified:

  self.mainViewController = aController; 

However, when the mainViewController frame is mainViewController , the self keyword is not required:

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

If I remove the self keyword from the first example, the program crashes with the message:

 objc[1296]: FREED(id): message view sent to freed object=0x3b122d0 

If I add the self keyword to the second example, the program will work fine.

Can someone explain why self is required in the first case, but not in the second? I assume that in both cases the mainViewController refers to the same instance variable.

+47
objective-c iphone cocoa-touch
Mar 05 '10 at 10:24
source share
2 answers

Using self forces the "setter" of your class to "call" this variable, rather than directly changing ivar.

 self.mainViewController = aController; 

equivalent to:

 [self setMainViewController:aController]; 

On the other hand:

 mainViewController = aController; 

it simply changes directly the instance variable mainViewController , skipping any additional code that can be built into the UIApplication setMainViewController method, for example, deleting old objects, saving new ones, updating internal variables, etc.

In the case when you access the frame, you still call the setter method:

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

expands to:

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

Ideally, for future proof of your code, you should also use self.mainViewController (or [self mainViewController] ) to get this value. In general, classes are much less likely to have important code in their "getter" methods than their "setters", but it is still possible that access could directly break something in a future version of Cocoa Touch.

+47
Mar 05 '10 at
source share

the self keyword indicates that you are using the getter / setter property instead of directly accessing the value. in case you let the auto-generator / setter automatically generate using synchronization, you should use self in the first example, because the object is stored there instead of a simple pointer.

+9
Mar 05 '10 at 10:32
source share



All Articles