05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Worse yet, the more ivars you add, the more you’re writing the same code over and over<br />

again.<br />

Objective-C 2.0 introduces explicitly named properties via a compact header syntax:<br />

#import <br />

@interface BMPerson : NSObject {<br />

NSString *name;<br />

NSUInteger age;<br />

}<br />

+ (BMPerson *)personWithName:(NSString *)aName age:(NSUInteger)anAge;<br />

@property (retain) NSString *name;<br />

@property (assign) NSUInteger age;<br />

@end<br />

That’s nice, but what’s really amazing is what this does for your implementation:<br />

#import "BMPerson.h"<br />

@implementation BMPerson<br />

+ (BMPerson *)personWithName:(NSString *)aName age:(NSUInteger)anAge;<br />

{<br />

BMPerson *newPerson = [[self alloc] init];<br />

newPerson.name = aName;<br />

newPerson.age = age;<br />

}<br />

return [newPerson autorelease];<br />

- (void)dealloc;<br />

{<br />

self.name = nil;<br />

}<br />

[super dealloc];<br />

@synthesize name, age;<br />

@end<br />

That’s a lot less code. For one thing, all the setter and getter method implementations have<br />

been replaced by one line:<br />

@synthesize name, age;<br />

CHAPTER 26 MAC <strong>OS</strong> X DEVELOPMENT: OBJECTIVE-C 509<br />

That compiler directive inserts the standard implementations, keeping you from having to<br />

type them over and over again. The generated implementations are faster than the handwritten<br />

ones and are executed atomically, meaning they are thread-safe. Better results for less work?<br />

That’s the Objective-C way.<br />

Dot syntax, on the other hand, is decidedly not the Objective-C way, yet when it comes to<br />

accessing and mutating property values, the compactness of dot syntax is actually nicer than the<br />

readability of Objective-C syntax. Objective-C 2.0 gives you the best of both worlds. Now you<br />

can use dot notation and simple assignment to get and set properties:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!