Search code examples
objective-cclassvariablesclass-methodclass-variables

How to setup a class property in objective C?


How to setup a class property that can be accessed throughout the app and from another classes in objective C?

Note: I know that there are other answers here at SO but most of then are outdated or torn apart! The question that is marked as being duplicate was asked 11 years ago ...!

Recently I had a project where dived deeper into this topic and I like to give you some code examples that may be helpful to someone out here. This is also some kind of information storage for myself :)


Solution

  • Since Xcode 8 you can define a class property in the header file of YourClass, using the "class" identifier like:

    @interface YourClass : NSObject
    
    @property (class, strong, nonatomic) NSTimer *timer;
    
    @end
    

    To use the class property in class methods in your implementation you need to asign a static instance variable to your class property. This allows you to use this instance variable in class methods (class methods start with "+").

    @implementation YourClass
    
    static NSTimer *_timer;
    

    You have to create getter and setter methods for the class property, as these will not be synthesized automatic.

    + (void)setTimer:(NSTimer*)newTimer{
        if (_timer == nil)
        _timer = newTimer;
    }
    
    + (NSTimer*)timer{
        return _timer;
    }
    
    // your other code here ...
    
    @end
    

    Now you can access the class property from all over the app and other methods with the following syntax - here are some examples:

    NSTimeInterval seconds = YourClass.timer.fireDate.timeIntervalSinceNow;
    
    [[YourClass timer] invalidate];
    

    You will always send messages to the same object, no problems with multiple instances!

    Please find an Xcode 11 sample project here: GitHub sample code