在Objective-C中,何时应该使用属性,何时应该使用实例变量? [英] In Objective-C, when should I use property and when should I use instance variable?

查看:73
本文介绍了在Objective-C中,何时应该使用属性,何时应该使用实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉具有属性和实例变量的程序语言。

所以我不知道使用属性和实例变量的好方法。

I'm not familiar with the program language which has both property and instance variable.
So I don't know good ways to use property and instance variable.

现在我只使用Objective-C代码中的属性而不使用任何实例变量。

Now I use only properties in my Objective-C code and I don't use any instance variables.

我是否需要使用实例变量?

或者只使用属性是Objective-C的最佳做法?

Do I need to use instance variable?
Or using only property is the best practice for Objective-C?

@interface ViewController : UIViewController
{
    // instance variable
    @public
    int a;
}

// property
@property(nonatomic, strong) NSString *b;

@end


推荐答案

使用到处都是物业甚至不要声明实例变量,而是像这样合成它们: @synthesize myProperty = _myProperty ,以便将它们与属性名称区分开来。属性也是处理内存管理的好方法。唯一必须使用合成实例变量的地方是 dealloc 方法。

这些属性的优点很多:

- 访问器方法定义了如何获取和设置实例变量的值。

- 您可以自定义访问器方法(例如,懒惰实例化ivar或做某事时设置一个新值,如 setNeedsDisplay

- 设置新值时无法处理内存管理 - setter负责释放/保留(取决于你如何申报财产 - 保留 / 复制 / 分配 / strong

- 一些带有 atomic / <的多线程内容code> nonatomic 属性

- 使用属性时,您可以利用 KVO

- 至少,但不是最后 - 如果您每次吸气或放气时都不关心性能问题ter被称为......

Use properties everywhere. Don't even declare instance variables, but synthesize them like this: @synthesize myProperty = _myProperty in order to differentiate them from property names. Properties are good way to cope with memory management as well. The only place you must use the synthesized instance variable is in the dealloc method.
The advantages of the properties are a lot:
- The accessor methods define how will you get and set the value of your instance variable.
- You can customize the accessor methods (for example to lazy instantiate an ivar or do something when a setting a new value like setNeedsDisplay.
- You don't cope with memory management when setting a new value - the setter takes care for releasing/retaining (depending how have you declared the property - retain/copy/assign/strong.
- Some multithreading stuff with the atomic/nonatomic attributes
- You can take advantage of the KVO, when using properties
- And least, but not last - don't worry about performance issues if you have concernes that every time a getter or a setter is called...

这篇关于在Objective-C中,何时应该使用属性,何时应该使用实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆