问题描述
有人可以向我解释一下(看起来是)一个额外变量的重要性,以及为什么要在一个与上一个名字相同的新变量之前加一个下划线.
Can someone explain to me the significance of creating (what seems to be) an extra variable and why put an underscore before a new variable with the same name as the last.
我已经读到它与创建实例变量有关,但是为什么要创建一个UI元素作为实例变量呢?您能提供一个用例吗?
I have read that it is to do with creating instance variables but why would you want to create a UI element as an instance variable? Can you please provide a use case?
此目标c代码用于iOS开发.
This objective c code for use in iOS development.
谢谢.
推荐答案
当您@synthesize
属性并且您不提供自己的getter和setter方法(在这种情况下,无需@synthesize
)时,就会出现始终是创建的新实例变量.默认情况下,它的名称与属性相同.因此,@synthesize slider;
在幕后创建了一个名为slider
的实例变量.
When you @synthesize
a property and you do not provide your own getter and setter methods (in which case there is no need to @synthesize
) then there is always a new instance variable created. By default it gets the same name as the property. So @synthesize slider;
makes an instance variable named slider
behind the scenes.
这里的问题是,当您确实打算使用self.slider = xxx
时,您可能会错误地键入slider = xxx
.当您将某个属性设为属性时,最佳实践表明您应始终通过self.propertyName
访问它(除了init和dealloc方法以及任何自定义的getter和setter方法中).
The problem here is that you might mistakenly type slider = xxx
when you really meant to use self.slider = xxx
. When you make something a property, best practice says you should always access it through self.propertyName
(except in your init and dealloc methods and any custom getter and setter methods).
因此,为了避免这种情况,使用@synthesize
语句将后备ivar重命名为更难以与该属性混淆的内容.如果现在使用slider
而不是self.slider
,则编译器将给出错误消息,因为slider
不再是实例变量的名称.
So in order to avoid this, the @synthesize
statement is used to rename the backing ivar into something that is harder to confuse with the property. If you now use slider
instead of self.slider
the compiler will give an error message because slider
is no longer the name of an instance variable.
这篇关于调用"@synthesize slide = _slider;"有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!