Direct access to auto-synthesized instance variables in subclasses?

房东的猫 提交于 2019-12-10 17:23:39

问题


For efficiency I want to access the member variable associated with a property in a subclass. If I have a property declared like:

@interface Mumbo : NSObject
    @property (nonatomic) GLKVector3 position;
@end

In the implementation of Mumbo I can refer to position either as self.position or directly as _position (the default synthesized member variable - I am not using @synthesize). I use the latter for efficiency in some cases to avoid copying structures.

However, in subclasses I cannot refer to _position unless I change the interface to

@interface Mumbo : NSObject {
    GLKVector3 _position;
}
    @property (nonatomic) GLKVector3 position;
@end

This seems to work. However, am I guaranteed that the automatically synthesized member variable will coincide with the one that I've explicitly declared in the braces? I can't find any definitive documentation on the subject.


回答1:


Auto-synthesized variables use a leading underscore be default, so you are right there.

But the way you declare your iVar - makes it public, but auto-synthesized variables are private. Which is why you can access it from outside the class.



来源:https://stackoverflow.com/questions/12234063/direct-access-to-auto-synthesized-instance-variables-in-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!