7.11. Accessor Methods

You have already met accessor method interfaces earlier in the chapter, but you are about to find out how you can implement them. Accessor methods are even more important in Objective-C than they are in other languages, like Java, because they are used for systematic memory management. If you follow this system, you will rarely have any problem with memory leaks or disappearing objects in your code. If you don't, you may end up in an Objective-C grade horror movie.

Actually, the reference to a horror movie is appropriate, because Cocoa provides a class called NSZombie for tracking down memory management problems in which objects are released too many times, or sent messages after they have been deallocated. NSZombie is a class that comes into play when you set the environment variable NSZombieEnabled to YES before running your program.

With the environment variable set, whenever an object is deallocated, its class is effectively changed to NSZombie. If a message is sent to the object after it has been deallocated, it will go to NSZombie, which will throw an exception telling you details of the mismanaged object.

There are actually several ways to write accessor methods. Each approach works, and it is up to you to choose the one that you are most comfortable with. To demonstrate some of the ways of writing accessors, consider the following class interface:

@interface WeatherConditions { float temperature; NSDate *date; WeatherStation *weatherStation; } -(float)temperature; ...

Get Beginning Mac OS® X Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.