每个伊娃都必须是财产吗? [英] Must every ivar be a property?

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

问题描述

我认为在为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.

所以我通常使用属性,但对于像 NSMutableArray 一个对象在 init 期间分配并用来容纳一堆whatevers,我将使用一个普通的旧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.

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

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