Does Cocoa provide a built-in method to convert a key string into a properly-formatted set property accessor? i.e. "lineSpacing" -> setLineSpacing:
For example:
NSString * key = @"lineSpacing";
SEL selector = [key magicallyConvertIntoSetPropertyAccessor];
or even:
NSString * key = @"lineSpacing";
SEL selector = NSSelectorFromString([key toSetPropertyAccessor]);
Background:
I'm working on a method that will set a number of properties, by name, using property values stored in a dictionary. I can't use setObject:forKey
because I also use this method for properties that are of built-in types like NSInteger
and CGFloat
. Here is an example of the method I use for CGFloat, to illustrate:
- (void)setFloatProperty:(NSString *)key value:(CGFloat)value target:(id)object
{
NSString * setPropertyString = [NSString stringWithFormat:@"set%@",
[key capitalizedString]];
SEL selector = NSSelectorFromString(setPropertyString);
NSMethodSignature * signature = ...
NSInvocation * invocation = ...
CGFloat arg = value;
void * argument = &arg;
[invocation setArgument:argument atIndex:2];
[invocation invoke];
}
This method works for one-word properties like "color" or "width", but fails on mulit-word properties like "lineSpacing" or "meaningOfLifeTheUniverseAndEverything" because the capitalize
method capitalizes the first letter while setting all subsequent letters to lowercase. Calling the above method using "lineSpacing" as the key results in failure, since the correct property setter would be setLineSpacing:
and not setLinespacing: