在@implementation而不是@interface定义的类变量? [英] Class variable defined at @implementation rather than @interface?
问题描述
我是Objective-C的新手,但我对自己在其他任何地方都没有真正解决过的问题感到好奇.
I'm new to Objective-C, but I am curious about something that I haven't really seen addressed anywhere else.
谁能告诉我在@interface
块处声明的私有变量与在类方法之外的@implementation
块内声明的变量之间的区别是什么?
Could anyone tell me what is the difference between a private variable that is declared at the @interface
block versus a variable that is declared within the @implementation
block outside of the class methods, i.e:
@interface Someclass : NSObject {
NSString *forExample;
}
@end
vs.
@implementation Someclass
NSString *anotherExample;
-(void)methodsAndSuch {}
@end
似乎两个变量(forExample
,anotherExample
)在整个类中都可以平等地访问,而我在它们的行为上并没有真正的区别.第二种形式也称为实例变量吗?
It seems both variables ( forExample
, anotherExample
) are equally accessible throughout the class and I can't really find a difference in their behaviour. Is the second form also called an instance variable?
推荐答案
后者未定义实例变量.而是在.m文件中定义全局变量.这样的变量对于任何对象实例都不是唯一的或一部分.
The latter is not defining an instance variable. Rather, it is defining a global variable in the .m file. Such a variable is not unique to or part of any object instance.
此类全局变量有其用途(大致等同于C ++静态成员;例如,存储一个单例实例),但是通常您会在@implementation指令之前在文件顶部定义它们.
Such globals have their uses (roughly equivalent C++ static members; e.g. storing a singleton instance), but normally you would define them at the top of the file before the @implementation directive.
这篇关于在@implementation而不是@interface定义的类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!