且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在类扩展中使用属性,而不是在ARC后使用ivar

更新时间:2023-01-02 21:29:25

对您的问题没有正确的答案,只有观点.因此,您会得到各种各样的答案,以下是您要添加到收藏夹中的一个答案:-)

不建议您使用私有财产,这在很大程度上是一种时尚. :-)

公共属性是类封装的一部分-如何实现属性(或方法)与用户无关,只有与行为无关./p>

一个类不需要从自身隐藏其实现方式!

因此,私有属性的唯一用例是它们以方便的方式为实现类提供一些行为,而不是隐藏该行为.

例如,如果某个类正在从另一个类获取可变字符串并且需要保留其当前值,则具有copy属性的私有属性可能会很方便.

如果类希望在需要时延迟构造一个值,但在此之后保留该值,则属性可以方便地处理该值.当然,方法或函数以及属性可以仅仅是方法调用.

要做出选择,请考虑便捷性/代码设计,而不是像对待公共属性那样封装.而且大多数时候,您可能只会使用实例变量,就像使用局部变量一样.

HTH

The recommended practice is to use property, including private ones through class extension instead of ivar (except in init and dealloc) in the post ARC environment.

Aside from it being a recommended practice, what are the main drawbacks in someone using ivar instead of property? I am trying to convince some folks to make the switch but some have argued ivar works just as well and faster. So I would like to collect good solid arguments rather than giving soft statements such as "it's better, more consistent, etc."

There is no right answer to your question, just opinions. So you'll get varying answers, here's one to add to your collection :-)

Using private properties is is not recommended practice, it is largely a fad. :-)

A public property is part of the encapsulation of the class - how a property (or method) is implemented is not relevant to the user, only the behaviour.

A class does not need to hide how it is implemented from itself!

So the only use cases for private properties is where they provide some behaviour in a convenient way to the implementation of the class, not to hide that behaviour.

A private property with the copy attribute may be convenient if the class is, say, obtaining mutable strings from another class and needs to preserve their current values.

If the class wishes to lazily construct a value if it is needed but keep it after that time then a property can handle that conveniently. Of course a method or function can as well as a property is after all just a method call.

To make the choice think convenience/code design rather than encapsulation as you do for public properties. And most of the time you'll probably just use instance variables, just as you just use local variables.

HTH