首页 > 代码库 > 【OC语法快览】二、存取方法

【OC语法快览】二、存取方法


Accessors

  存取方法


All instance variables are private in Objective-C by default, so you should use accessors to get and set values in most cases. There are two syntaxes. This is the traditional 1.x syntax:

OC中所有的实例变量默认是私有的,所以多数情况下你应该使用访问器来获得和设置实例变量的值。访问器有两种语法。下面说的是传统的1.x版本:
 
[photo setCaption:@"Day at the Beach"];
output = [photo caption];
The code on the second line is not reading the instance variable directly. It‘s actually calling a method named caption. In most cases, you don‘t add the "get" prefix to getters in Objective-C. 

上面的第二行代码不是直接读取实例变量值,实际上是调用了名叫caption的方法。多数情况下,你不要OC的取值方法中添加"get"前缀。

Whenever you see code inside square brackets, you are sending a message to an object or a class.

每当你看到中括弧中得代码时,你正在给一个类或实例对象发送消息。
 

Dot Syntax

  点语法

The dot syntax for getters and setters is new in Objective-C 2.0, which is part of Mac OS X 10.5:

存取方法的点语法是在OC 2.0版中作为Mac OS X 10.5的一部分新加入的。
 
photo.caption = @"Day at the Beach";
output = photo.caption;
You can use either style, but choose only one for each project. The dot syntax should only be used setters and getters, not for general purpose methods.

你可以使用以上两种方式,但一个项目只能选用一种方式。点语法不适用于普通用意的方法,只能用作设值和取值方法,也就是存取方法。




原文:learn_objective_C part 2