乐趣区

Objective-C-如何选择@property-和-Instance-Variable(iVar)

简述
在 Objective- C 的类中, 有两种方式可以声明变量
@property:
// 在 .h 文件
@interface Hello : NSObject
@property (nonatomic, strong) UIView *view;
@end

或者
// 在 .m 文件
@interface Hello()
@property (nonatomic, strong) UIView *view;
@end

实例变量 Instance Variable (iVar):
// 在 .h 文件里
@interface Hello () {
UIView *_view;
}
@end

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

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

什么时候用 @property, 什么时候用 iVar 呢?
区别
可见性
如果想要定义私有 (private) 变量, 可以考虑使用 iVar; 定义公开 (public) 变量, 则使用 @property;
iVar 虽然可以用 @private, @protected 和 @public 修饰, 但只会对影响到子类的可见性. 也就是说, 即使你用 @public 修饰 iVar, 其它类也是无法访问到该变量的.
属性(attributes)
@property 可以使用 strong, weak, nonatomic, readonly 等属性进行修饰.
iVar 默认都是 strong.
书写习惯
通常, iVar 名称使用下划线开头, 如 _view, _height, _width. 但这并非强制要求.
getter/setter
编译器自动为 @property 生成访问器(getter/setter).
效率
iVar 运行效率更高.
结论
如果只是在类的内部访问, 既不需要 weak、retain 等修饰词, 也不需要编译器自动生成 getter/setter 方法, 则使用 variable 就可以. 否则就使用 @property.
参考资料:http://hongchaozhang.github.i…
https://www.quora.com/Objecti…

退出移动版