R – Is is possible to define a class property in Objective-C?


To declare an instance property you can use a declaration similar to this:

@property (readonly) int size;

The property can later be accessed using the dot syntax:

NSLog(@"The object has a size of: %d", objectInstance.size);

However, I'd like to declare a class property so that, even without an instance, I can access it in this manner. For example:

NSLog(@"%d instances have been created.", ClassName.numberOfInstances);

I know I could always implement this behaviour using a class message and call it using the dot syntax anyway, but I'd prefer having a declared property and would benefit from the @synthesize directive for some of the properties.

Is this possible?

Best Solution

The short answer is that no, you can't. The compiler will not let you do it. You can see that when Apple has to do something similiar (like for the UIView implicit animation parameters) they use KVC compliant naming put do not declare them as properties.

The longer answer is that classes are objects and I can in fact envision some pretty grotesque hacks that involve proxy redirections that let you do it, but it is really not something I would recommend doing.