An accessor method is an instance method that gets or sets the value of a property of an object. In Cocoa’s terminology, a method that retrieves the value of an object’s property is referred to as a getter method, or “getter;” a method that changes the value of an object’s property is referred to as a setter method, or “setter.” These methods are often found in pairs, providing API for getting and setting the property values of an object.
You should use accessor methods rather than directly accessing state data because they provide an abstraction layer. Here are just two of the benefits that accessor methods provide:
You don’t need to rewrite your code if the manner in which a property is represented or stored changes.
Accessor methods often implement important behavior that occurs whenever a value is retrieved or set. For example, setter methods frequently implement memory management code and notify other objects when a value is changed.
Because of the importance of this pattern, Cocoa defines some conventions for naming accessor methods. Given a property of type
type and called
name, you should typically implement accessor methods with the following form:
The one exception is a property that is a Boolean value. Here the getter method name may be
isName. For example:
This naming convention is important because much other functionality in Cocoa relies upon it, in particular key-value coding. Cocoa does not use
getName because methods that start with “get” in Cocoa indicate that the method will return values by reference.