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.

With that accomplished, you can return your newly instantiated self to be assigned to the<br />

waiting pointer:<br />

return self;<br />

Another way to go about this would have been to create an init method that lets the caller<br />

pass in the name and age values in one line, not unlike the factory method example earlier:<br />

- (id)initWithName:(NSString *)aName age:(NSNumber)anAge;<br />

{<br />

if (![super init])<br />

return nil;<br />

}<br />

[self setName:aName];<br />

[self setAge:anAge];<br />

return self;<br />

A new person could then be initialized with custom values:<br />

[[BMPerson alloc] initWithName:@"Mike Lee" age:31];<br />

Since someone might still call init, it still has to be implemented, but now it can just call the<br />

new method:<br />

- (id)init;<br />

{<br />

return [self initWithName:nil age:0];<br />

}<br />

Every class will typically have one init method to which all other init methods refer. This is<br />

called the designated initializer. Subclasses of that class should call the designated initializer,<br />

rather than just calling init. The bad news is, you usually can’t tell which is the designated initializer<br />

without checking the documentation. The good news is, Objective-C doesn’t rely on<br />

subclassing as much as other languages do, so it’s less of a problem in practice.<br />

NOTE Since this new initializer is not declared in the superclass, you would also have to add<br />

its declaration to the header file.<br />

As objects are born, so must they die. Just as init gives your objects a chance to get things<br />

in order before being used, dealloc gives them a chance to get their affairs in order before they’re<br />

sent off to that big memory heap in the sky.<br />

- (void)dealloc;<br />

{<br />

[name release];<br />

name = nil;<br />

}<br />

[super dealloc];<br />

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

In our case, we’ve got a pointer, name, that needs to be released. Whenever releasing an<br />

object in dealloc, or anywhere else, set the pointer to nil. You never know what might happen,<br />

especially in the crazy world of multithreaded, multiprocessor computing. You don’t want to<br />

leave a dangling pointer around for someone to call and crash.

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

Saved successfully!

Ooh no, something went wrong!