且构网

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

我应该在实施中使用自我关键字(属性)吗?

更新时间:2023-02-06 17:43:48

首先,您不应根据Apple文档(出于充分的理由)在init或dealloc中使用setter或getter.

First, you should not use setters or getters in init or dealloc according to Apple documentation (and for good reasons).

除此之外,如果有变量,通常应该使用setter来设置变量.

Other than that, you should generally use the setter for setting the variable if there is one.

通常,我不会在实现中使用getter来访问ivar,但是有时候有必要这样做.特别是,如果您希望getter可以进行一些计算或检查,或者您希望允许子类覆盖其行为.

Usually I do not bother using the getter for accessing the ivar from within the implementation, but there are times when it is necessary. In particular, if you expect the getter might do some caclulation or checking, or if you want to allow for subclasses to override the behaviour.

当然,在实现中使用getter更通用,更安全,但通常也没有意义和浪费.做出选择.

Certainly, using the getter in the implementation is more general and safer, but it is also typically pointless and wasteful. Make your choice.

使用设置器非常重要,因为它为其他代码提供了观察更改的关键(观察关键值),并且子类有机会覆盖设置器并进行任何其他需要的调整.

Using the setter is important as it gives an opertunity for other code to observe the changes (Key Value Observing), as well as subclasses a chance to override the setter and make any other adjustments required.

但是,我强烈建议您为ivar和财产使用一个不同的名称.常规约定是下划线前缀(_),尽管我本人使用i_作为前缀,以避免与Apple的私人用法混淆.这样一来,您就不会意外使用错误的密码:

However one thing I highly recommend is to use a different name for your ivar and your property. The normal convention is an underscore prefix (_), although I personally use i_ as the prefix to avoid any confusion with Apple's private usage. That way you cannot accidently use the wrong one:

self.name // use property
i_name // use ivar
self.i_name // syntax error
name // syntax error