本文介绍了在目标c中访问属性的自我和下划线之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在self和下划线之间访问Objective c中的属性,无论何时我们创建属性,它的getter-setter都会自动生成。因此,我们可以使用self.property访问相同的属性,并且与_property相同。在我看来,应该有一些不同之处,我没有得到。请告诉我一些例子。

I am so confused between self and underscore to access the property in Objective c, whenever we create property, its getter-setter automatically generated. So we can access the same property with self.property and same as _property. In my opinion, there shoulb be some difference which i am not getting. PLease tell me with examples.

推荐答案

下划线(下划线)版本是实际的实例变量,不应直接引用。你应该总是通过属性名称,这将确保任何getter / setter操作都得到尊重。

The underbar (underscore) version is the actual instance variable, and should not be referenced directly. You should always go via the property name, which will ensure that any getter/setter actions are honoured.

所以如果你做 _property = 4 ,您已直接设置变量。如果你执行 self.property = 4 ,你实际上正在调用方法 [self setProperty:4] ,将通过setter(可能会执行诸如强制执行属性最大值为3的操作,或更新UI以反映新值)。

So if you do _property = 4, you have directly set the variable. If you do self.property = 4, you are effectually making the method call [self setProperty:4], which will go via the setter (which might do something such as enforce property having a max value of 3, or updating the UI to reflect the new value, for example).

这篇关于在目标c中访问属性的自我和下划线之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 14:50