如何从Objective-C中的另一个类访问@public实例变量? [英] How to access @public instance variable from another class in Objective-C?
问题描述
我知道可以使用@public关键字定义公共实例变量. 但是,Objective-C语法不允许访问其他类的变量. 我应该从@public Ivar获得什么功能?或如何访问其他班级的Ivar?
I know it's possible to define public instance variable with @public keyword. However, Objective-C syntax does not allow accessing other class' variable. What features should I expected from @public Ivar? Or how do I access other class' Ivars?
推荐答案
Objective-C作为C的超集,绝对允许从类的实现之外访问公共实例变量.现在,您可能听说过不允许的原因是,强烈建议您不要使用它.在大多数情况下,如果要在实现上下文之外访问实例变量,则应使用访问器和修改器(属性).
Objective-C, as a superset of C, definitely does allow the access of public instance variables from outside the class's implementation. Now, the reason you may have heard that it isn't allowed is that it is highly discouraged. In most cases, if you want to access an instance variable outside an implementation context, you should be using accessors and mutators (properties).
Objective-C类实际上可以归结为带有isa
字段(这就是使其成为对象)的普通C结构,可以在其中访问公共字段.因为当我们处理类的实例时,我们正在处理一个指向对象(特殊结构)的指针.因此,我们使用->
访问公共字段.
An Objective-C class really boils down to a plain-old C struct with an isa
field (that's what makes it an object), where the public fields are accessible. Since when we are dealing with instances of classes, we are working a pointer to an object (special struct). Thus, we access public fields using ->
.
这是一个例子:
@interface SomebodyIsntEncapsulating : NSBadIdea {
@public
NSString *badIdea;
BOOL shouldntDoIt;
@protected
NSString *ahThatsBetterThankGod;
@private
NSString *sweetThanksNowEvenMySubclassesCantTouchMe;
}
现在,在某些完全不同的情况下,我们可以:
Now, in some completely different context, we could have:
SomebodyIsntEncapsulating *whatOh = [[SomebodyIsntEncapsulating alloc]
initWithDanger:kDangerLevelEpicBraceYourself];
whatOh->badIdea = [@"I'm a public field. Make sure to retain or copy me!" copy];
NSLog(@"Please! Write some accessors and mutators!: %@", whatOh->badIdea);
希望对您有所帮助!
这篇关于如何从Objective-C中的另一个类访问@public实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!