prabodhprakash prabodhprakash - 24 days ago 4
Objective-C Question

declaring variable in implementation (.m) file

If my implementation file looks like below

int someIntVariable;

@implementation SomeClass

- (void) foo {
someIntVariable = 0;
}

@end


What is the behaviour of
someIntVariable
. Is it static to this implementation class or instance level? and how is it accessible outside the file?

Rob Rob
Answer Source

Because someIntVariable is defined outside of the @interface (which you haven’t included here), that means that it is not an instance variable. It's a global.

And because you omitted the static keyword, it means that this variable is technically available to any other compilation unit, though they'd have to define their own extern reference to it:

extern int someIntVariable;

If you wanted to prevent that, i.e. make this private to this particular compilation unit, you'd include the static keyword in the original declaration of someIntVariable in SomeClass.m:

static int someIntVariable;

Note, you've defined this global variable outside of the @implementation. But it's worth noting that the above still applies if it was inside the @implementation, too. It exhibits the exact same behavior as your example (a global variable, not a instance variable, that other compilation units could manipulate without your knowledge) if it was inside the @implementation:

@implementation SomeClass

int someIntVariable;

- (void) foo {
    someIntVariable = 0;
}

@end

Bottom line, if you wanted static behavior but wanted to make sure it couldn't be manipulated by external compilation units, you'd declare it to be a static, as shown above. And obviously, if you want an instance variable, you'd declare this in the @interface (either explicitly declare instance variable or, more common now, declare property and let the compiler synthesize the ivar for you).