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.io/blog/2015/07/22/Property-vs-Instance-Variable(iVar)-in-Objective-C/

https://www.quora.com/Objective-C-programming-language-What-is-the-difference-between-an-instance-variable-and-a-property

原文地址:https://www.cnblogs.com/ZJT7098/p/13984498.html