在类扩展中使用属性,而不是在ARC后使用ivar [英] Use property in class extension instead of ivar in post ARC

查看:61
本文介绍了在类扩展中使用属性,而不是在ARC后使用ivar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐的做法是在后ARC环境中使用属性,包括通过类扩展的私有属性,而不是ivar(在init和dealloc中除外).

除推荐做法外,使用ivar而不是属性的人的主要缺点是什么?我试图说服某些人进行转换,但有些人则认为ivar可以同样好且更快地工作.因此,我想收集好的可靠论据,而不是给出诸如更好,更一致等"之类的软性陈述.

解决方案

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

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

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

这篇关于在类扩展中使用属性,而不是在ARC后使用ivar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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