05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

510<br />

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

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

worldsToughestProgrammer.name = @"Mike Lee";<br />

NSLog(@"%@ is the world's toughest programmer.", worldsToughestProgrammer.name);<br />

Mike Lee is the world's toughest programmer.<br />

Notably, properties do not prevent you from using standard syntax:<br />

[worldsToughestProgrammer setName:@"Mike Lee"];<br />

Nor do they prevent you from using KVC syntax:<br />

[worldsToughestProgrammer setValue:@"Mike Lee" forKey:@"name"];<br />

Properties, like scalars, are automatically initialized to nil, so you don’t have to do that in<br />

init, which means, in this case, you don’t need init at all. You also don’t have to explicitly<br />

release your pointers or remember to set them to nil. You can just set the property to nil, which<br />

will do both.<br />

Should you decide to change the way a property behaves, you can just change the property<br />

attributes themselves. The compiler will do the right thing when it comes to the @synthesize<br />

directive. There are three classes of property behavior; see Table 26-4.<br />

Table 26-4. Objective-C 2.0 Property Attributes<br />

Behavior Values Notes<br />

Memory management retain, assign, copy The default is assign.<br />

Mutability readonly, readwrite The default is readwrite.<br />

Thread safety nonatomic atomic is assumed.<br />

The Objective-C way is to make things easy but to allow you to do things the hard way if<br />

necessary. Properties are the same way. If, for example, you have a property whose instance variable<br />

does not have the same name, you can connect the two explicitly. For example, if, in<br />

BMPerson, you called the property age but the ivar years, you could note this in your @synthesize<br />

directive:<br />

@synthesize name, age = years;<br />

If you wanted to override the setter of the age property to provide validation, all you have<br />

to do is implement it:<br />

- (void)setAge:(NSUInteger)anAge;<br />

{<br />

if (anAge > 0 && anAge < 100)<br />

age = anAge;<br />

}<br />

Even though you’ve asked the compiler to synthesize this property, it will see that you’ve<br />

implemented it yourself and do the right thing.<br />

In the converse of assigning an ivar, you can also, if necessary, explicitly assign a setter or<br />

getter in the property declaration:<br />

@property (assign, getter=ageInYears) NSUInteger age;

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

Saved successfully!

Ooh no, something went wrong!