views:

37

answers:

1

I've come across Objective-C code that declares a variable right below the @implementation line in a .m file and not in the @interface block of the .h file. It then proceeds to use it like a private ivar. I haven't been able to find documentation about declaring variables this way and would like to know the impact.

Example:

.h

@interface MyClass {
    @private
    int _myPrivInt1;
}
@end

.m

@implementation
int _myPrivInt2;
@end

Questions:

What is the technical difference between these two variables?

Is it the same as declaring an ivar in the .h @interface block using the @private modifier or is it more like a C global variable?

Are there any implications when declaring a variable this way?

Should it be avoided?

Is there a term for declaring variables like _myPrivInt2 that would have made my googling a bit more successful?

+1  A: 

You must declare instance variables in interface block.

@implementation
int _myPrivInt2;
@end

Declaring variable this way you do not actually declare iVar for your class. _myPrivInt2 will be a global variable and can be accessed from any part of your code using extern declaration:

// SomeOtherFile.m
extern int _myPrivInt2;
...
_myPrivInt2 = 1000;

You can check - your _myPrivInt2 variable will be equal 1000 after code in SomeOtherFile.m executes.

You can also specify static linkage specifier to your _myPrivInt2 so it will be accessible inside current translation unit only

@implementation
static int _myPrivInt2; // It cannot be accessed in other files now
@end
Vladimir
I tested your extern idea and it behaved as you described. This is the reassurance I needed. What made this ambiguous is that the global variable is declared within the @implementation block which, to me, seems to indicate that it belongs to the class somehow.
Sebastien Martin
indeed, that is confusing thing. But all variables declared outside the function bodies become global regardless of were they declared inside @implementation block or not
Vladimir
Hmm, interesting. Do you still need to import your .h file in SomeOtherFile.m to make this work? I'm hoping for a "yes"...
Altealice
no, you don't need to import any header - you declare _myPrivInt2 variable in SomeOtherFile.m with external specifier - so linker will look for that instance defined something else
Vladimir