What is the proper way to declare static variables in Objective-C?

Mark A. Donohoe picture Mark A. Donohoe · Feb 14, 2012 · Viewed 9.1k times · Source

Ok, still re-adjusting to things when switching between C, C++, C# and Objective-C so sometimes my head spins. This time however, I'm more confused as to the proper way since I have seen at least three different ways to declare static variables in Objective-C, and there's a fourth if you consider it's just a superset of C itself. So which of these is right?

Additional Question

If we want to share a stand-alone variable (i.e. not a static class variable, but one just defined in a header) is that done the same way as in 'C' (ala with 'extern' in the header?)


Option A

Foo.h

@interface Foo : NSObject{
    static int Laa;
}

@end

Foo.m

@implementation Foo
    ...
@end

Option B

Foo.h

@interface Foo : NSObject{
}

@end

Foo.m

static int Laa; // <-- Outside of the implementation

@implementation Foo
    ...
@end

Option C

Foo.h

@interface Foo : NSObject{
}

@end

Foo.m

int Laa; // <-- Note no word 'static' here like in 'Option B'

@implementation Foo
    ...
@end

Option D

Foo.h

static int Laa;

@interface Foo : NSObject{
}

@end

Foo.m

@implementation Foo
    ...
@end

Option E

Foo.h

@interface Foo : NSObject{
}

@end

Foo.m

@implementation Foo

    static int Laa;

    ...

@end

Bonus question...

Do you have to use the word extern or is that only when you are using .c/.c++ files, not .m/.mm files?

Answer

Inder Kumar Rathore picture Inder Kumar Rathore · Feb 14, 2012

The Option A is wrong. Objective -c class doesn't have a static varibale.
Option B and E are the correct way to implement static variables.
Option C creates a global variable that might be accessed out side the implementation file using extern keyword.
Option D again creates a global static variable which can be accessed from anywhere by just importing .h file.
About your bonus question: extern keyword has the same meaning as in C/C++.