简体   繁体   English

ARC:成员变量和属性之间有什么区别?

[英]ARC: what's the difference between a member variable and property?

I have an NSArray object that is used throughout my UIViewController. 我有一个在我的UIViewController中使用的NSArray对象。 I can either declare it as an ivar or as a property. 我可以将其声明为ivar或属性。 Is there any advantage to either approach (considering I'm using ARC)? 两种方法都有什么优势(考虑到我使用的是ARC)?

Option 1: 选项1:

@interface MyViewController {
    NSArray *_myArray;
}
@end

Option 2: 选项2:

@interface MyViewController
    @property (strong, nonatomic) NSArray *myArray;
@end

Properties and ivars are conceptually quite different. 属性和ivars在概念上完全不同。

A property represents a logical component of your code. 属性代表代码的逻辑组成部分。 It may, but need not, be backed by an ivar. 它可能但不需要由ivar支持。 It could be dynamically generated calculated at run-time (like a view's -frame ), etc. 它可以在运行时 动态生成 计算(如视图的-frame ),等等。

An ivar is an actual allocated block of memory holding some data. ivar是保存一些数据的实际分配的内存块。

If you use properties (correctly), you get nice features like KVC/KVO compliance out of the box. 如果正确使用属性,则开箱即用即可获得不错的功能,例如KVC / KVO合规性。 For this and other reasons it is often thought to be good practice, especially with the modern run-time, to declare all public interfaces in the form of properties, and internally back them with ivars (frequently using @synthesize ) if appropriate. 由于这个和其他原因,通常认为是一种好习惯,尤其是在现代运行时,以属性的形式声明所有公共接口,并在适当时在内部使用ivars(经常使用@synthesize )对其进行支持。

Personally, I prefer to use properties for private data as well, both to make it easy to make public later if I want (just move the declaration to the header!) and to make it easy to provide custom implementations of properties (and setters/mutators) instead of relying on a simple ivar. 就个人而言,我也喜欢将属性用于私有数据,既可以方便以后在需要时公开(只需将声明移到标头!),也可以轻松提供属性(和setter /变数),而不是依赖简单的ivar。

Since you mention ARC, I haven't used it much (yet) but I don't think it should make much of a difference as long as you declare your property correctly. 自从您提到ARC以来,我还没有使用太多(但是),但是我认为只要您正确地声明了属性,它就不会有太大的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM