I'd like to have class-level properties, and I found a solution from https://stackoverflow.com/a/15811719/157384
@interface Model
+ (int) value;
+ (void) setValue:(int)val;
@end
@implementation Model
static int value;
+ (int) value
{ @synchronized(self) { return value; } }
+ (void) setValue:(int)val
{ @synchronized(self) { value = val; } }
@end
and now you're able to call through property accessors, like so:
Model.value = 1
Model.value // => 1
Fantastic!
Now, I want to make this chunk of code reusable, in some form of macro or meta-programming, that takes a property name and type. How can we write it?
With the example above, value
and (int)
(and Model
) should be dynamic.
Update
Thanks to @Rich I now have this:
// Common.h
#define CLASS_PROPERTY_INTERFACE(TYPE, METHOD, CMETHOD) \
+ (TYPE) METHOD; \
+ (void) set##CMETHOD:(TYPE)val; \
#define CLASS_PROPERTY_IMPLEMENTATION(TYPE, METHOD, CMETHOD) \
static TYPE _##METHOD; \
+ (TYPE) METHOD \
{ @synchronized(self) { return _##METHOD; } } \
+ (void) set##CMETHOD:(TYPE)val \
{ @synchronized(self) { _##METHOD = val; } } \
// User.h
@interface User : NSObject
CLASS_PROPERTY_INTERFACE(User *, me, Me)
@end
// User.m
@implementation User
CLASS_PROPERTY_IMPLEMENTATION(User *, me, Me)
@end
User.me = currentUser;
User.me // => currentUser
One thing left to be done is to automatically capitalize the method name passed to the macro, if at all possible.
But it's already much more succinct than the boilerplate as it stands!