Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Accessor method
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.
Naming Conventions
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:
- (type)name; |
- (void)setName:(type)newName; |
The one exception is a property that is a Boolean value. Here the getter method name may be isName
. For example:
- (BOOL)isHidden; |
- (void)setHidden:(BOOL)newHidden; |
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.
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06