int helloness;
@interface test : NSObject
@end
vs
@interface test : NSObject{
int helloness;
}
@end
Do I understand that following are true and the only meaningful differences between the above two blocks:
- in both blocks, the implementation of
test.mcan usehellonessvariable internally, like an ivar - in the first block,
hellonesswill exist for any class that imports this.hbut is otherwise private only totest.min the second block
In the first block, is this technically what is considered a “global variable” in that any class that imports this will have access to the same contents of helloness?
What happens if multiple header files have a declaration for helloness and you import them all?
Similar to this, consider this implementation:
@implementation AClass
int food=5;
Here, food acts like an internal iVar, even though it was not declared in any @interface ?
In your first example,
hellonessis a global variable. It can be seen by any file which imports that header. If you include multiple headers which also declare anint hellonessvariable, I believe you’ll get a warning from the compiler, and all of them will point at the same memory location. If you include another header which declares ahellonessof type other thanint, I believe you’ll get a compiler error.In the second example,
hellonessis an instance variable (ivar). Its value (memory location) is specific to each instance ofAClass. (Anything can access it: e.g.AClass *instance = [[AClass alloc] init]; instance->helloness = 7;However, direct access to ivars is generally avoided in ObjC — we use accessors and/or properties instead.)In the third case,
foodis still a global variable, but its visibility is restricted to the implementation file it’s declared in. Any instance ofAClass, as well as any other classes or categories or functions implemented in the same file, can referencefood, and all those references are to the same memory location.