Search code examples
iphoneobjective-ciosipadmodifier

Objective-C Modifers for static?


How do I create a static variable in my Objective-C class? I'm familiar with using @private in my header files for private variables, but I am trying to create a static method which accesses a static variable. How should I declare this static variable in my header file?


Solution

  • Objective-C doesn't have static class variables. You can create module-static variables (just as in C), however. To have a private, static variable:

    //MyClass.m
    static int MyStatic;
    
    @implementation MyClass
    @end
    

    will give MyStatic module-level scope. Because this is just C, there's no way to make MyStatic visible from, e.g. categories on MyClass without making it publicly visible via an extern declaration. Since static variables are effectively global variables, this is probably a good thing—MyClass should be doing absolutely everything it can to hide the existence of MyStatic.

    If you want the static variable to be public (you really don't want to):

    //MyClass.h
    extern int MyStatic;
    
    @interface MyClass {}
    @end
    
    //MyClass.m
    int MyStatic;
    
    @implementation MyClass
    @end