How to use global variables in Objective-C?

前端 未结 4 675
谎友^
谎友^ 2020-12-05 10:58

How should I declare a global variable in my Objective-C project?

4条回答
  •  有刺的猬
    2020-12-05 11:19

    In my experience there are few instances when a program doesn't need, at least, some sort of data or utility/helper methods that can be accessed throughout the program.

    They way I deal with this, rather than using global variables is to create what I call a 'project applicance', which is essentially just a class with a bunch of static methods.

    It could be implemented multiple ways, but I use a singleton and just have the static methods call through to the single instance of the appliance class. For example, in my project Oovium I have:

    Oovium.h:

    @interface Oovium : NSObject {
        UIWindow* _window;
    }
    
    + (UIWindow*) window;
    

    Oovium.m:

    @implementation Oovium
    
    static Oovium* oovium;
    
    - (UIWindow*) window {return _window;}
    
    + (void) initialize {
        oovium = [[Oovium alloc] init];
    }
    
    + (UIWindow*) window {return [oovium window];}
    

    I then include Oovium.h in my Oovium_Prefix.pch file so that it is automatically included in all of my files.

提交回复
热议问题