Sebastien Martin
Sebastien Martin

Reputation: 1379

Undeclared ivars?

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?

Upvotes: 2

Views: 350

Answers (1)

Vladimir
Vladimir

Reputation: 170829

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

Upvotes: 3

Related Questions