在Objective-C的類中,有兩種方式能夠聲明變量git
// 在 .h文件 @interface Hello : NSObject @property (nonatomic, strong) UIView *view; @end
或者github
// 在 .m文件 @interface Hello() @property (nonatomic, strong) UIView *view; @end
//在 .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
@property 能夠使用strong, weak, nonatomic, readonly 等屬性進行修飾.get
iVar默認都是strong.編譯器
一般, iVar名稱使用下劃線開頭, 如 _view, _height, _width.
但這並不是強制要求.it
編譯器自動爲@property生成訪問器(getter/setter).
iVar 運行效率更高.
若是隻是在類的內部訪問, 既不須要weak、retain等修飾詞,也不須要編譯器自動生成getter/setter方法, 則使用 variable就能夠.不然就使用 @property.