Skip to content

Instantly share code, notes, and snippets.

@yenchenlin
Last active August 29, 2015 14:23
Show Gist options
  • Save yenchenlin/c8707d810709661f40aa to your computer and use it in GitHub Desktop.
Save yenchenlin/c8707d810709661f40aa to your computer and use it in GitHub Desktop.
What is @Property ?

What is @property ?

@property 是 Obj-C 2.0 版開始提供的一種功能,目的是要簡化一個 instance variable 的設定過程。

為什麼需要 @property ?

instance variable (以下簡稱 ivar ) 在 Obj-C 裡預設為 protected , 代表只有這個 class or 它的 subclass 可以 access 值。 如果這個 ivar 要給外部使用的話,那就必須必須加上 public 的 method setter/getter。 然而,每宣告一個要給外部使用的 ivar 就要宣告一組 setter/getter 太麻煩,因此 Obj-C 加入了 @property 的語法 。

舉例來說,原本想讓外部的人使用 weight 要這樣寫:

@interface Apple : NSObject {
	int weight;
}
- (int)weight;
- (void)setWeight:(int) w;
@end

並且在 @implementation 中實作 setter/getter

@implementation
- (int)weight {
  return weight;
}
- (void)setWeight:(int)w {
  weight = w;
}
@end

然而,使用 @property 的話,只需要:

@interface 	Apple : NSObject
@property int weight;
@end

這段 code 的實際效用等於

@interface Apple : NSObject {
	int _weight;
}
- (int)weight;
- (void)setWeight:(int)weight;
@end
@implementation Apple : NSObject
- (int)weight {
	return _weight
}                                     
- (void)setWeight:(int)weight {
	_weight = weight;
}
@end

@property 跟 ivar 的關係

其實call @property propertyName 時,等於是宣告了一個 ivar 叫 _propertyName。

例如上面例子,宣告 @property int weight時,ivar的名字是_weight,而非weight

ivar 會如此命名是因為 Xcode 4.4 版以後,若沒有在 @implementation 裡特別 call @synthesize ,則Xcode 會自動預設 @synthesize propertyName = _propertyName。

@property 帶來的方便

用 @property 宣告值後,我們也可以更方便的用 . 來 access 該值,例如:

theApple 是一個用 Apple 宣告的 object,theApple.weight 會用 getter access 該值,theApple.weight = 100 則會 call setter 來改值。

Override setter & getter

使用 @property 之後還是可以 override setter 與 getter,用 propertyName 做為 getter 名稱,而用 setPropertyName:propertyName 做為 setter 名稱,不必宣告方法。

setter function name 因為在 propertyName 前面加上 set,因此 propertyName 第一個要改成大寫

例如:

@interface Apple : NSObject  
@property int weight;
@end

@implementation Apple
- (void)setWeight:(int)weight { 
	if(weught < 0) weight = 0; 
	if(weight > 300) weight = 300;
    _weight = weight; 
}
@end

這樣一來,就可以保護 weight 不被改寫成負數或大於 300 得值。

@written by jason lin

@bcylin
Copy link

bcylin commented Jun 26, 2015

  • 建議 code 可以調整一下,空格的位置要保持 consistency
  • Markdown 的 code block 後面加上 objc 可以顯示 syntax highlighting

@yenchenlin
Copy link
Author

Fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment