Cocoa Core Competencies_Accessor method

注: 该系列文章翻译自iOS Developer Library –> Cocoa Core Competencies

Cocoa Core Competencies, 顾名思义 Cocoa核心概念。只是各个部分概念介绍, 更加详尽的学习, 参见各个章节提供的相关链接。

译者水平有限, 难免存在各种问题, 欢迎指正交流。

欢迎转载, 转载请注明出处: Colin

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.

存取方法是一个可以获得(get)或者设置(set)一个对象的属性值的实例方法。在Cocoa的术语中,一个检索对象属性值的方法被称为getter方法,或者"getter;",一个改变对象属性值的方法被称为setter方法,或者“setter.”这些方法通常成对建立,提供获得(get)或者设置(set)对象属性值的API。

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:

因为这种模式的重要性,Cocoa定义了一些命名存取方法的规则。给出一个属性的类型type和称呼name,你应该通过下面的格式,来实现存取方法:
- (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:

有个例外是属性为Boolean值。getter方法名字应该是isName。例如:
- (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.

    这种命名惯例很重要,因为在Cocoa中的很多其他的功能都依赖它,特别是key-value coding。Cocoa不使用getName因为以get开始的方法表明方法返回引用类型的值。

Prerequisite Articles

Key-value coding

Related Articles

Memory management

Declared property

Definitive Discussion

Use Accessor Methods to Get or Set Property Values in Programming with Objective-C

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。