Search code examples
objective-cstaticdeclared-property

Declare a static property in an Objective-C class interface


I'm defining an Objective-C class:

@interface MyRequest : NSObject

@property (strong, nonatomic, readonly) NSDecimalNumber *myNumber;

@property (strong, nonatomic, readonly) CommConfig *commConfig;

@property (nonatomic, assign, readonly) BOOL debug;

How do I make commConfig a static variable? When I use the 'class' keyword, the compiler gives me the following warning:

Class property 'commConfig' requires method 'commConfig' to be defined - use @dynamic or provide a method implementation in this class implementation

And the constructor doesn't recognize this line anymore:

_commConfig = commConfig

Solution

  • If not implemented by the programmer instance properties are automatically implemented by the compiler - an instance variable allocated and getter and/or setter methods written. Class properties are never automatically implemented, you therefore need to declare the static backing variable and define the getter. In your @implementation add:

    static CommConfig *_commConfig;
    
    + (CommConfig *) commConfig { return _commConfig; }
    

    You can call the backing anything you wish, e.g. to follow a naming convention for global/static variables.

    HTH