Reputation: 2147
I want to write a macro to generate 2 methods like below:
- (NSString*)propertyName
{
NSString *key = @"PropertyName";
//get value from NSUserDefaults
//...
}
- (void)setPropertyName:(NSString*)value
{
NSString *key = @"PropertyName";
//set value to NSUserDefaults
//...
}
The first letter of property name is lower case in the get method, upper case in the set method and key value.
The macro should receive 1 or 2 arguments which is the property name:
MY_PROPERTY(propertyName)
or
MY_PROPERTY(PropertyName)
or
MY_PROPERTY(propertyName, PropertyName)
The argument is also the value for key
(string value).
How to write a macro for this? I prefer the first or second one. Thanks.
Upvotes: 1
Views: 499
Reputation: 130162
Let's get mad:
#define STRINGIFY(__TEXT__) [NSString stringWithFormat:@"%s", (#__TEXT__)]
#define GENERATE_GETTER_AND_SETTER(__UPPER_CASE__, __LOWER_CASE__, __TYPE__) \
- (void)set##__UPPER_CASE__:(__TYPE__)__LOWER_CASE__ { \
NSString *propertyName = STRINGIFY(__UPPER_CASE__); \
\
...
} \
\
- (__TYPE__)__LOWER_CASE__ { \
NSString *propertyName = STRINGIFY(__UPPER_CASE__); \
\
...
return ... \
} \
Usage:
GENERATE_GETTER_AND_SETTER(MyProperty, myProperty, NSArray*)
Note that you have to specify both lower case and upper case names and you have to know the type of the property.
It might be easier to declare the properties as @dynamic
and then implement the methods dynamically, see Objective-C forwardInvocation: for more details.
Upvotes: 4