Objective-C-如何選擇@property-和-Instance-Variable(iVar)

簡述

在Objective-C的類中,有兩種方式能夠聲明變量git

  • @property:
// 在 .h文件
@interface Hello : NSObject
@property (nonatomic, strong) UIView *view;
@end

或者github

// 在 .m文件
@interface Hello()
@property (nonatomic, strong) UIView *view;
@end
  • 實例變量 Instance Variable (iVar):
//在 .h文件裏
 @interface Hello () {
UIView *_view;
}
@end

或者segmentfault

//在 .m文件 的interface裏
@interface Hello () {
UIView *_view;
}
@end

或者atom

//在 .m文件 的implement裏
@implement Hello  {
UIView *_view;
}
@end

何時用@property, 何時用 iVar呢?url

區別

可見性

若是想要定義私有(private)變量, 能夠考慮使用iVar; 定義公開(public)變量,則使用@property;code

iVar雖然能夠用 @private, @protected@public 修飾, 但只會對影響到子類的可見性.也就是說,即便你用 @public修飾iVar, 其它類也是沒法訪問到該變量的.blog

屬性(attributes)

@property 能夠使用strong, weak, nonatomic, readonly 等屬性進行修飾.get

iVar默認都是strong.編譯器

書寫習慣

一般, iVar名稱使用下劃線開頭, 如 _view, _height, _width.
但這並不是強制要求.it

getter/setter

編譯器自動爲@property生成訪問器(getter/setter).

效率

iVar 運行效率更高.

結論

若是隻是在類的內部訪問, 既不須要weak、retain等修飾詞,也不須要編譯器自動生成getter/setter方法, 則使用 variable就能夠.不然就使用 @property.

參考資料:
http://hongchaozhang.github.i...

https://www.quora.com/Objecti...

相關文章
相關標籤/搜索