Question

I'd wrote a preprocessor define statement for a getter method

#define GetNSStringDefaultForPropertyWithNameAndKey(propertyName, propertyKey) - (NSString *)propertyName { return [[NSUserDefaults standardUserDefaults] objectForKey:_userDefaultsKey][propertyKey];  }

but got stuck when doing the same for the setter method as I'd have to modify propertyName argument to setPropertyName.

Is there way to do this kind of argument modification.

EDIT I should have said that both definitions should overwrite the compiler generated getter/setter methods. But if I got Matthias right, the only way is to provide a capitalized version of the property in question like so.

#define SetNSStringDefaultForPropertyWithNameAndKey(PropertyName, propertyKey) - (void)set  ## PropertyName:(NSString *)newValue \  
{ \  
    self.userDefaults[propertyKey] = newValue; \
    [self updateUserDefaults]; \
} \
Was it helpful?

Solution

You can use ## to concatenate two tokens together. However the preprocessor can't change the case of a token. So you have to provide a uppercase property name yourself.

Something like this should work

#define SetNSStringDefaultForPropertyWithNameAndKey(propertyName, propertyKey) - (void)set ## propertyName:(id)object { [[NSUserDefaults standardUserDefaults] objectForKey: _userDefaultsKey][propertyKey] = object; }

And because the preprocessor can't change to uppercase you have to provide the property name with the first letter capitalized

SetNSStringDefaultForPropertyWithNameAndKey(Foobar, @"foobar")

GetNSStringDefaultForPropertyWithNameAndKey(foobar, @"foobar")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top