Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve named objects denoted by NSStrings?

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?

like image 699
timpone Avatar asked Apr 13 '26 12:04

timpone


2 Answers

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];

You can try something like this:

SEL myColor = NSSelectorFromString([NSString stringWithFormat:@"%@Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
like image 25
Simon Germain Avatar answered Apr 15 '26 00:04

Simon Germain