How do I retrieve named objects denoted by NSStrings?
ios, objective-c
Solution
A nearly universal way:
NSDictionary *colors = @{
@"red": [UIColor redColor],
@"green": [UIColor greenColor],
@"blue": [UIColor blueColor]
};
NSString *name = @"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:@"%@Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
Problem
I have a set of NSString values like this: ``` self.dataArray = @[@"blue", @"orange", @"green", @"red", @"yellow"]; ``` and would like to be able to do something like (after getting one of the above colors set to self.colorString): ``` self.view.backgroundColor=[UIColor self.colorString + Color]; ``` but obviously can't do that. What is a possible way?