问题
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