Direct access to auto-synthesized instance variabl

2019-06-26 13:06发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-06-26 13:19

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.

查看更多
登录 后发表回答