Chapter 12. Accessors and Memory Management
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.
Accessors are important in part because instance variables, by default, are protected (Chapter 5), whereas publicly declared methods are public; without public accessor methods, a protected instance variable can’t be accessed by any object whose class (or superclass) isn’t the one that declares the instance variable. You might be tempted to conclude from this that you needn’t bother making an accessor for an instance variable that isn’t intended for public access, and to some extent this is a reasonable conclusion. But here are some counterarguments:
- Cocoa often uses the string name of an instance variable to derive the name of the accessor and call it if it exists. Thus there needs to be an accessor so that Cocoa can find it.
- If your app doesn’t use ARC, and if your instance variable is an object, there are going to be memory management tasks to worry about every time you get and (especially) set that value; the best way to ensure that you’re carrying out those tasks reliably and consistently is to pass through an accessor.
- Even if your app does use ARC, there may be additional tasks that need to be performed every time the instance variable’s value is touched; an accessor, acting as a gateway to the instance variable, ...
Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.