Search code examples
objective-cglobal-variablesstatic-variables

Application-wide variable access: static like Java?


I have an instance variable in my view controller that I would like to share with the whole program. I'm not quite sure how to do this. Can I just declare it as a static instance variable and then access it through properties like ViewControllerClass.instancevariable?

Thanks!


Solution

  • In reply to your comment attached to the question:

    If you have an instance variable in Object X, any other object that has a reference to X can access that variable through the usual means:

    [objectX myClassAInstanceVariable];
    // Or, if declared with @property
    objectX.myClassAInstanceVariable;
    

    If the other object doesn't have a reference to X, then it can't access the variable, no matter the state or kind of the variable. In this case, you may want to rethink your design, or see my last paragraph below about the app delegate.


    The concept of "static" is different in Objective-C than what you may be expecting (it sounds like you're coming from experience with Java).

    Objective-C doesn't really have a concept of "class variables", although it is fairly easy to simulate such a thing; this is described in the question that mathk linked to: Objective-C Static Class Level variables. You declare a variable in the class's header file which is static, so that it is inaccessible outside that file, and create accessor class methods for it.

    Any object that has a reference to your view controller can send messages to it. Note that in Objective-C, member variables are "protected" by default, meaning that only an instance of a class or subclasses, not other objects, can access those variables. Other objects must go through setter and getter methods.


    Just as another option, because the background of your question is not clear, if you have some kind of a "global variable" which isn't really specific to your view controller, a better place to put it may be the application delegate*. Any object can get a reference to the delegate at any time:

    [NSApp delegate];
    

    NSApp is a global reference to the NSApplication object which is at the core of your program.


    *Although it's certainly possible to overdo this.