Objective-C:何时调用self.myObject vs只调用myObject [英] Objective-C: When to call self.myObject vs just calling myObject
问题描述
在Objective-C中,这一点语法对我来说有点混乱。
This little bit of syntax has been a bit of a confusion for me in Objective-C.
我什么时候应该调用self.myObject vs只调用myObject?
When should I call self.myObject vs just calling myObject?
这似乎是多余的,但它们不可互换。
It seems redundant however they are not interchangeable.
有人可以开导我吗?
推荐答案
如果您只是访问它们,则没有太多理由使用 self.member
。如果你正在进行任务,那么你做的不仅仅是简单的 @property(assign)
参数 - 例如,保留,复制等,所以它可以节省您正在编写的代码。例如:
If you're just accessing them, there's not much reason to use self.member
. If you're doing assignment, it's good if you're doing more than the simple @property (assign)
parameter--for instance, retain, copy, etc, so it can save on code you're writing. An example:
myObject = anotherObject;
self.myObject = anotherObject;
第二个选择将确保您实际按照自己的方式分配对象(获取副本) ,增加保留计数等)。它与 [self setMyObject:anotherObject]
没有区别。
The second choice will ensure that you're actually assigning the object the way you want (getting a copy, increasing the retain count, etc.). It's no different from [self setMyObject:anotherObject]
.
由于点符号被替换为消息编译器(类似于 x [5]
如何在常规中变为 *(x + 5 * sizeof(x))
数组工作),使用点符号比常规消息没有开销或额外的效率。
Since the dot-notation gets substituted for a message by the compiler (similar to how x[5]
becomes *(x + 5*sizeof(x))
in regular array work), there's no overhead or extra efficiency in using dot-notation over regular messages.
这篇关于Objective-C:何时调用self.myObject vs只调用myObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!