且构网

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

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

更新时间:2023-02-06 18:32:46

首先,根据 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.

使用 setter 很重要,因为它为其他代码提供了一个观察更改的操作(键值观察),以及子类有机会覆盖 setter 并进行任何其他所需的调整.

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