自变量和变量之间的区别
可能的重复:
类属性 mVar 和实例变量 self.mVar 之间的差异< /a>
我是 Objective-C 开发新手,我不太清楚以下内容之间有什么区别:
首先让我解释一下我的情况。我有一个 NSMutableArray,并在 .h 文件中为其创建了出口。现在,当我向它分配一个数组时,
self.myMutableArray=myArray
我收到一个错误;不过
myMutableArray=myArray
效果很好。
我对解决错误不感兴趣。我只是想知道将 self
放在某物前面有什么区别?为什么我也可以在没有 self
的情况下使用该变量?它带来了哪些限制?
Possible Duplicate:
Difference between class property mVar and instance variable self.mVar
I am new to developing in Objective-C and I couldn't quite figure out what the difference is between the following:
First let me explain my situation. I've got an NSMutableArray
, and I created and outlet for it in my .h file. Now when I assign an array to it as
self.myMutableArray=myArray
I get an error; However just
myMutableArray=myArray
works fine.
I am not interested in the resolving of the error. I just want to know what is the difference when putting self
in front of something? And why I am able to use the variable also without self
and what restrictions that brings with it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
等于:
也就是说,使用
self.
的声明是通过对象的访问器方法,而不是使用直接访问。它们有不同的原因和影响。也许最值得注意的是,如果不小心使用,直接访问通常会导致引用计数问题(泄漏/僵尸)。访问器负责处理内存管理 - 如果是综合的,或者如果您自己实现的话。
一般规则:您应该倾向于使用访问器 (
self.blah = thing;
) 而不是直接访问 (blah = thing;
),直到您知道何时以及为什么要对这条规则做出例外。直接例外:一般规则有一个例外:不要在部分构造状态下使用访问器,例如对象的初始值设定项或dealloc。在这些情况下,请使用直接访问:
更新
描述 Bvarious 对错误的怀疑:
听起来您已声明了实例变量,但尚未声明关联的属性或正确的属性访问器(例如设置器)。以下是包含 ivars 和属性的类声明的详细说明:
is equal to:
That is to say, the declaration using
self.
goes through the object's accessor method, rather than using direct access.They have different causes and effects. Perhaps the most notable is that direct access will often leads to reference count issues (leaks/zombies) if not used with care. The accessor is responsible for handling memory management - if synthesised, or if you implement it yourself.
The General Rule: You should favor using the accessors (
self.blah = thing;
) over direct access (blah = thing;
) until you know when and why you would make exceptions to this rule.The immediate exception: There is one exception to the general rule: Do not use the accessors in partially constructed states, such as the object's initializer or
dealloc
. In those cases, use direct access:Update
Describing Bavarious' suspicion of the error:
It sounds like you have declared an instance variable, but have not declared an associated property or proper accessors (e.g. the setter). Here's a breakdown of a class' declaration with ivars and properties:
self.variable 是在 .h 文件中定义的属性,就像在 .m 中一样
,
而
定义
只是“变量”在 .h 中
self.variable is a property defined in the .h file like so
and
in the .m
whereas just "variable" is defined as
in the .h