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.

NOTE In Java, you can override ivars with arguments, because you can distinguish them with<br />

the keyword this. So, you could say this.name == name. Objective-C doesn’t have this nicety<br />

(or hassle, depending on your point of view).<br />

In a way, setters are written backward. You’re setting the value of the pointer to a new<br />

object, which you will retain:<br />

name = [aName retain];<br />

Doing so will remove your ability to reach the old object, so you must first release it:<br />

[name release];<br />

However, if the old object and the new object are the same, you might end up causing the<br />

object to be freed, which would cause a crash when you tried to use it. As such, before you can<br />

do any of this, you need to check that the two objects are, in fact, not the same, and bail out if<br />

they are:<br />

if (name == aName)<br />

return;<br />

With all the fuss, it seems like it would be a lot easier to just access the variables directly and<br />

not hassle with calling methods. However, there’s a good reason not to; it’s a violation of<br />

encapsulation.<br />

Encapsulation is an important part of object-oriented programming. It states that implementation<br />

details should always be hidden. This prevents objects from becoming entangled and<br />

making things just as complicated as they were with procedural programming. It also protects<br />

programmers from implementation changes.<br />

For example, consider the setter for age:<br />

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

{<br />

age = anAge;<br />

}<br />

Right now it’s very simple. It takes a scalar type rather than a pointer, so we don’t even have<br />

to worry about memory management. What if you later decide that blithely setting this value is<br />

a security risk because of integer overflow exploits? To protect against that, you add some validation<br />

logic:<br />

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

{<br />

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

age = anAge;<br />

}<br />

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

If you’ve been good and respected encapsulation, your work is done. If you’ve been bad and<br />

have been setting the variable directly, you’re going to have a lot of implementation work ahead<br />

of you. That’s why it’s always a good idea to use setters and getters, even from within the object<br />

itself.<br />

NOTE In the section on Objective-C 2.0, you’ll read about <strong>Leopard</strong>’s new property syntax,<br />

which makes writing setters and getters yesterday’s hassle.

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

Saved successfully!

Ooh no, something went wrong!