Chapter 12. Accessors and Memory Management

Even when you’ve understood how to slot in your code so as to get the messages that you want from Cocoa (Chapter 11), your obligations to Cocoa and your interactions with the framework are not over. You have additional responsibilities that emerge as you write the code for any class that will be instantiated. There are guidelines for how a well-behaved instance should be structured and how it should act — in fact, I seriously thought of calling this chapter “The Well-Behaved Instance.” If you don’t follow those guidelines, things can go wrong: outlets aren’t set, the wrong methods are called, memory gets used up, your app crashes. This chapter is about those guidelines.

Accessors

An accessor is a method for getting or setting the value of an instance variable. An accessor that gets the instance variable’s value is called a getter; an accessor that sets the instance variable’s value is called a setter.

There are naming conventions for accessors, and you should obey them. The conventions are simple:

  • A setter’s name should start with set and be followed by a capitalized version of the instance variable’s name. If the instance variable is named myVar, the setter should be named setMyVar:. The setter should take one parameter: the new value to be assigned to the instance variable.
  • A getter should have the same name as the instance variable. If the instance variable is named myVar, the getter should be named myVar. (This will not cause you or ...

Get Programming iOS 5, 2nd Edition now with O’Reilly online learning.

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