直接访问子类中自动合成的实例变量? [英] Direct access to auto-synthesized instance variables in subclasses?
问题描述
为了效率,我想访问与子类中的属性关联的成员变量.如果我有一个属性声明如下:
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
在 Mumbo 的实现中,我可以将 position 称为 self.position 或直接称为 _position(默认的合成成员变量 - 我没有使用 @synthesize).我在某些情况下使用后者来提高效率以避免复制结构.
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.
推荐答案
自动合成的变量默认使用前导下划线,所以你就在那里.
Auto-synthesized variables use a leading underscore be default, so you are right there.
但是您声明 iVar 的方式 - 将其公开,但自动合成的变量是私有的.这就是为什么你可以从课堂外访问它.
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.
这篇关于直接访问子类中自动合成的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!