Use of properties by Xcode 4 templates

I little while ago I posted about some techniques to remove duplicate code when declaring instance variables (see DRYing your instance variables). When I wrote that post I had not managed to take a look at the new templates provided in Xcode 4. It turns out that Apple has changed the code generated by the templates to use a very similar approach (which is reassuring to me at least).

For example if you create a new project based on the Utility Application template the interface for the Application Delegate class looks like this:

@class MainViewController;
@interface UtlityAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MainViewController *mainViewController;
@end

The instance variables are not explicitly declared instead they rely on a feature of Objective-C 2.0 and the modern runtime to synthesize them along with the getter/setter methods. The relevant synthesize statements from the implementation file are as follows:

@synthesize window=_window;
@synthesize mainViewController=_mainViewController;

Here another feature of the language is used to make the name of the instance variable different from the name of the property. So the property named “window” will in its getter/setter methods refer to an instance variable named “_window”. I covered why this is a good idea in an earlier post but in short it makes it clear when you are referring to the instance variable directly and when you are using the getter/setter methods. The dealloc method is one place where you generally want to avoid the getter/setters and access the instance variable directly. This should now be clear from the dealloc method generated by the Xcode templates:

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

In general it also seems that the template generated code is much more consistent about accessing instance variable via self rather than directly. Apologies if I seem to be beating this topic into the ground but I think it is important and it is interesting to see the approach that Apple is now promoting in the templates.

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories