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