如何检索NSStrings表示的命名对象?

时间:2013-08-03 05:45:53

标签: ios objective-c

我有一组像这样的NSString值:

self.dataArray = @[@"blue", @"orange", @"green", @"red", @"yellow"];

并且希望能够做类似的事情(在将上述颜色之一设置为self.colorString之后):

self.view.backgroundColor=[UIColor self.colorString + Color];

但显然不能那样做。什么是可能的方式?

3 个答案:

答案 0 :(得分:7)

近乎通用方式:

NSDictionary *colors = @{
    @"red": [UIColor redColor],
    @"green": [UIColor greenColor],
    @"blue": [UIColor blueColor]
};

NSString *name = @"blue";
UIColor *c = colors[name];

真正的通用方式:

NSString *selName = [NSString stringWithFormat:@"%@Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];

答案 1 :(得分:2)

您可以尝试这样的事情:

SEL myColor = NSSelectorFromString([NSString stringWithFormat:@"%@Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]

答案 2 :(得分:1)

尝试将您的数据与词典中的颜色相关联:

UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];

NSDictionary *colors = @{@"blue" : blue, @"red" : red};

UITextField *pinga = [[UITextField alloc]init];

pinga.textColor = [colors objectForKey:@"red"];