user1695758
user1695758

Reputation: 173

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

Upvotes: 0

Views: 4087

Answers (1)

CRD
CRD

Reputation: 53000

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

Upvotes: 1

Related Questions