都必须是一个属性吗

都必须是一个属性吗

本文介绍了每个 ivar 都必须是一个属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到在为 iOS 编码时到处都建议使用属性来访问实例变量,因为这有利于内存管理等.

I see it recommended all over the place when coding for iOS that properties should be used for accessing instance variables because of the benefits this lends to memory management, among other things.

这个建议不太适合我.我发现使用属性而不是普通的旧 ivars 只会占用太多代码,如果您对内存管理感到满意,我并没有真正看到好处.真的有那么重要吗?您管理实例变量的方法是什么?

This advice doesn't sit terribly well with me. I find that using properties instead of plain old ivars just takes too much code and I don't really see the benefits if you're comfortable with memory management. Is it really that important? What's your approach to managing instance variables?

推荐答案

并不是真的有必要为所有 ivars 声明属性.我想到了几点:

It's not really necessary to declare properties for all ivars. A few points come to mind:

  • 如果一个 ivar 在对象的生命周期内只被分配一次,那么通过声明一个属性你并没有真正获得任何东西.只需在 init 期间保留/复制/分配,然后在 dealloc 期间根据需要释放.
  • 如果要频繁更改 ivar,声明一个属性并始终使用访问器将更容易避免内存管理错误.
  • 如果属性和 ivars 是私有的,您可以在 .m 文件而不是 .h 文件的类扩展中声明属性.
  • 针对 iOS 4.0+ 时,如果您定义了属性并合成了访问器,则根本不需要在标头中声明 ivars.
  • If an ivar is only going to be assigned to once during the lifetime of the object, you don't really gain anything by declaring a property. Just retain/copy/assign during init and then release as necessary during dealloc.
  • If an ivar is going to be changed frequently, declaring a property and always using the accessors will make it easier to avoid memory management errors.
  • You can declare properties in a class extension in the .m file rather than the .h file if the properties and ivars are meant to be private.
  • When targeting iOS 4.0+, you don't need to declare ivars at all in your header if you define a property and synthesize accessors.

所以我通常使用属性,但是对于对象在 init 期间分配并用来保存一堆东西的 NSMutableArray 之类的东西,我将使用一个普通的旧的 ivar,因为我永远不会重新分配 ivar.

So I generally use properties, but for things like a NSMutableArray that an object allocates during init and uses to hold a bunch of whatevers, I'll use a plain old ivar since I'll never be reassigning the ivar.

这篇关于每个 ivar 都必须是一个属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:17