我不确定如何使用objectAtIndex执行此操作

时间:2012-12-06 19:38:57

标签: objective-c ios

  

可能重复:
  how to convert nsstring to uicolor?

不是一个客观的程序员,但我不确定我是不是可以做这样的事情。我知道我正在返回一个字符串值,但只是想要一种简洁的方法来获取这些值:

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];
 // val5 is either 0 or 1
[view setBackgroundColor:[UIColor [colorsArray objectAtIndex:val5]]];

这可能吗?

事先提前

3 个答案:

答案 0 :(得分:5)

为什么不直接存储颜色而不是NSString

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:[UIColor whiteColor]];
[colorsArray addObject:[UIColor blueColor]];
if (val5 < colorsArray.count) // Doesn't hurt any to be safe, and this way you won't get a crash if something messes up your val5 at some point
{
    // val5 is either 0 or 1
    [view setBackgroundColor:[colorsArray objectAtIndex:val5]];
}
else
{
    NSLog(@"Error - Color not expected - leaving color the way it is.")
}

您编写的代码不会编译,语法无效,因为您尝试执行的[UIColor @"whiteColor"]不是有效的语法。您可以使用performSelector:,但这是毫无意义的,除非您确实需要将颜色存储为字符串。

答案 1 :(得分:3)

或者,如果您必须在数组中使用NSString个实例:

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];

SEL colorSelector = NSSelectorFromString([colorsArray objectAtIndex:val5]);
[view setBackgroundColor:[UIColor performSelector:colorSelector]];

答案 2 :(得分:2)

NSMutableArray *colorsArray = [[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];
UIColor *color = [UIColor performSelector:NSSelectorFromString([colorsArray objectAtIndex:1])];
view.backgroundColor = color;