例如,在以下代码中。
@interface TUTViewController : UIViewController
{
NSTimer *timer;
}
@end
和
@interface TUTViewController : UIViewController
@property (weak, nonatomic) NSTimer *timer;
@end
在哪种情况下我们使用第一种方法来声明变量?
例如,在以下代码中。
@interface TUTViewController : UIViewController
{
NSTimer *timer;
}
@end
和
@interface TUTViewController : UIViewController
@property (weak, nonatomic) NSTimer *timer;
@end
在哪种情况下我们使用第一种方法来声明变量?
你会得到很多关于这个的意见,通常被称为硬性规则。
例子:
Maddy:永远不要将 ivars 放在 .h 中。ivars 应该始终是私有的,这意味着它们不属于公共 .h。如果您创建 ivars,请将它们放在 .m 文件中
我非常尊重麦迪,但在这一点上我不同意他的观点。
如果将 iVar 放在 .m 文件中,它们对其他类是隐藏的,但它们对您创建的子类也是隐藏的。
我更喜欢将我的实例变量标记为@protected,这使得它们可用于子类,但不能用于其他类。
其他人会告诉你让一切都成为财产。在 ARC 之前,将所有对象保存在属性中是有意义的,因为您可以使用属性上的 setter 来管理对象上的内存。(当为保留的属性分配值时,setter 将首先释放任何旧值,然后保留新值。)现在 ARC 甚至为 iVar 也为您处理了这一点,因此将所有内容都设为属性的论点较少。
我所做的是让一切都成为 iVar,除非:
作为一项政策,我从不访问另一个对象的 iVar,除非通过属性。
使用属性而不是实例变量会产生少量但实际的开销。属性读/写总是进行方法调用。iVar 直接访问内存,没有方法调用的开销。通常,差异太小而无关紧要。但是,如果您正在执行数百万次操作,例如对大图像中的每个像素执行某些操作,或者处理来自实时处理视频或音频样本的回调,则差异可能会很大。
I would highly suggest to use @properties unless there is a very good reason not to. It's true the discussion is a religious one more than a technical one but since we are probably all followers of the Cult of Mac, if Apple prefers you to use @properties then that's the standard. In my opinion both Apple documentation and Xcode aren't as pushy on standards like ReSharper would do in Visual Studio for instance (it warns when you don't use var for example). That's a pity because that would make it easier for me to pick up code after somebody else.
There is a way to "hide" @properties in a .m file, you should declare it as follows:
@interface ABCMySpiffyClass ()
@property (weak, nonatomic) IBOutlet UIImageView *spiffyImage;
@property (weak, nonatomic) IBOutlet UILabel *spiffyTitle;
@end
These are not completely private to another consumer of your class but it is hidden at first sight. This should tell the other developer that he or she should not use them. I think public/private has more to do with documentation as it has to do with application security for most apps.