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.

494<br />

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

As with init, you’re overriding your superclass’s implementation. Sending a dealloc message<br />

to super will give everyone in the inheritance tree a chance to take care of their final business<br />

as well. With init, we typically call super first. In dealloc, we call super last.<br />

With the inherited hassle of memory management out of the way, you can finally get back<br />

to all those instance methods you declared.<br />

Instance Methods<br />

The whole point of object-oriented programming is to transfer responsibility to your objects.<br />

Whereas a functional programmer might say, “I am going to do something with this,” an objectoriented<br />

programmer would say, “I am going to ask this to do something.” The tasks we can ask<br />

our objects to do are their instance methods.<br />

The most common instance methods are for directly accessing and mutating an object’s<br />

instance variables. In technical terms, we call these methods accessors and mutators, but Apple<br />

prefers the more colloquial setters and getters. Whatever you call them, these methods follow a<br />

standard pattern.<br />

- (NSString *)name;<br />

- (void)setName:(NSString *)aName;<br />

In Objective-C, a getter has the same name and return type as the ivar it’s accessing and<br />

takes no arguments. The setter adds the prefix set to the name, takes one argument of the ivar’s<br />

type, and returns nothing. For the special case of Boolean ivars, the getter may use the prefix is.<br />

For example, calling isHidden would access the ivar hidden.<br />

NOTE Some languages will precede the ivar name with the word get, but in Objective-C, you<br />

use that pattern for something else.<br />

At its simplest, a getter just returns the value of the ivar:<br />

- (NSString *)name;<br />

{<br />

return name;<br />

}<br />

Because of memory management, setters are a bit more complicated:<br />

- (void)setName:(NSString *)aName;<br />

{<br />

if (name == aName)<br />

return;<br />

}<br />

[name release];<br />

name = [aName retain];<br />

The first thing you’ll notice is a setter’s argument cannot have the same name as its ivar.<br />

Looking at the first line explains why that is:<br />

if (name == aName)<br />

If you had given the argument the same name, you’d end up with this:<br />

if (name == name)<br />

Wouldn’t that be confusing?

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

Saved successfully!

Ooh no, something went wrong!