tags:

views:

174

answers:

3

I am working my way through some Objective-C code that I did not write and have found a variable declaration style that I am unfamiliar with. Can anyone tell me the scope of the variable 'myVar' in the class implementation below? Note that this appears in the '.m' file and not the interface declaration.

@implementation MyClass
@synthesize ivar1, ivar2;

NSString* myVar; // <- What is the intent?

- (id)init {

...

@end

To me the intention appears to be similar to that of a member variable. What are the advantages of declaring a variable in this way instead of using an ivar in the @interface declaration?

+9  A: 

It's just a plain old global variable. There's only one instance of it, and it can be accessed by any code within the same file translation unit (the final file you get after running the preprocessor). Other translation units (that is, other .m files) can also access that global variable, but in order to do so, they need to use an extern statement:

extern NSString *myVar;

extern says "this is the name of a global variable, but it's defined in a different translation unit". The linker resolves all of the extern declarations at link time.

Adam Rosenfield
+2  A: 

a poorly named global variable...

kent
To be fair to the original programmer - I did rename the variable to something generic for the purposes of this post.
teabot
fairness is cool. (und under-rated here at S.O.)
kent
+1  A: 

I'm not too experienced in ObjC but I'd say that is a global.

Morothar