@synthesize variable = _variable 会做什么?
例如,我在 iPhone 项目的应用程序委托中看到过类似的代码。
带下划线的变量是什么意思?我可以将它用作变量的 setter 和 getter 吗?
另外,在释放变量时我应该使用:
[variable release];
或
[_variable release];
谢谢。
I have seen code like that in the Application delegate in iPhone project for example.
what is the variable with the underscore means? can I use it as setter and getter for the variable?
also when releasing the variable should I use:
[variable release];
or
[_variable release];
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某些编码约定中,实例变量之前使用下划线可以快速将它们与其他变量区分开来。它还有助于避免与方法和子类方法中的局部变量的命名冲突。
创建一个 setter 和 getter 来设置/获取您设置的变量(在本例中为 _variable)。因此外部访问使用像 object.variable 这样的代码,它实际上只是返回 _variable。然而,该类通常在内部使用 _variable。
In some coding conventions the underscore before instance variables is used to be able to quickly differentiate them from other variables. It also helps avoid naming conflicts with local variables in methods and subclass methods.
Creates a setter and getter that set/get the variable you set it to in this case _variable. So outside access uses code like object.variable which is really just returning _variable. however the class usually uses the _variable internally.
属性名称为“variable”,支持它的实例变量名为“_variable”。您应该使用访问器
-variable
和-setVariable:
而不是直接访问 ivar,除了在 -init 和 -dealloc 中,您可以在其中使用_variable< /代码>。
The property name is "variable" and the instance variable that backs it up is named "_variable". You should use the accessors
-variable
and-setVariable:
rather than accessing the ivar directly, except in -init and -dealloc, where you'd use_variable
.在您的示例中,变量是一个属性,而 _variable 是一个实例变量。为了简单起见,我们可以说,通过综合,您本质上是在指示属性(在我们的例子中为变量)将使用实例变量(在我们的例子中为 _variable)来存储和检索值。您真正要做的是指示编译器创建与属性声明中给出的规范相匹配的实现。
当您使用属性时,建议的释放方式是将其分配为零。这实际上会释放该对象并将实例变量设置为 nil 而不是悬空指针。
如果您没有使用属性,那么您可以调用实例变量的release,然后理想情况下您希望将其设置为nil。
In your example variable is a property and _variable is an instance variable. For simplicity sake we can say that by synthesizing you are essentially instructing that the property ( in our case variable) will use the instance variable ( in our case _variable) for storing and retrieving values. What you are really doing is instructing the compiler to create implementations that match the specification given in the property declaration.
The suggested way of releasing when you are using a property will be to just assign it nil. This would essentially release the object and also set the instance variable to nil instead of being a dangling pointer.
If you were not using property then you can call the release on the instance variable and then ideally you want to set it to nil.