Objective c 调用objectAtIndex方法以获取随机颜色时出现问题

Objective c 调用objectAtIndex方法以获取随机颜色时出现问题,objective-c,arc4random,Objective C,Arc4random,初学者学习objective-c,请原谅基本错误 目标是将predictionLabel.textColor设置为数组中的随机颜色 // fill array colors self.colors = @[@"redColor", @"greenColor", @"blueColor", @"greyColor", @"orangeColor", @"purpleColor"]; // get random number based on array count int randomColor

初学者学习objective-c,请原谅基本错误

目标是将
predictionLabel.textColor
设置为数组中的随机颜色

// fill array colors
self.colors = @[@"redColor", @"greenColor", @"blueColor", @"greyColor", @"orangeColor", @"purpleColor"];

// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);

// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [UIColor [self.colors objectAtIndex:randomColor]];
我一直在
[UIColor[self.colors
处收到错误消息“Expected identifier”


作为新手,我很难排除这个问题。有什么建议吗?

虽然你想使用键值编码,但你没有使用。你实际上只是猜测
UIColor
上可能存在的方法名称。为什么不使用
UIColor
对象数组而不是类方法的名称。如下所示:

self.colors = @[[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor grayColor], UIColor orangeColor], [UIColor purpleColor]];

// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);

// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [self.colors objectAtIndex:randomColor];

另外,请注意“灰色”与“灰色”的拼写不存在。

虽然您想使用键值编码,但您没有使用键值编码。您实际上只是在猜测
UIColor
上可能存在的方法名称。为什么不使用
UIColor
对象数组而不是类方法的名称。如下所示:

self.colors = @[[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor grayColor], UIColor orangeColor], [UIColor purpleColor]];

// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);

// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [self.colors objectAtIndex:randomColor];

另外,请注意“灰色”与“灰色”的拼写。
[UIColor greyColor]
不存在。

您要做的是:

[UIColor @"redColor"];
它不会编译,也不是有效的语法

如果坚持使用字符串,则可以执行以下操作:

self.predictionLabel.textColor = [UIColor valueForKey:[self.colors objectAtIndex:randomColor]];

你想做的是:

[UIColor @"redColor"];
它不会编译,也不是有效的语法

如果坚持使用字符串,则可以执行以下操作:

self.predictionLabel.textColor = [UIColor valueForKey:[self.colors objectAtIndex:randomColor]];

更重要的是,结果只有在运行时才知道。更重要的是,结果只有在运行时才知道。方法的结果不能用作编译时常量。我认为您考虑过这样的情况…
self.predictionLabel.textColor=[[UIColor class]performSelector:NSSelectorFromString(randomColor)]这是一段可怕的代码。请使用Aaron的答案。方法的结果不能用作编译时常量。我认为您考虑到了类似的情况…
self.predictionLabel.textColor=[[UIColor类]performSelector:NSSelectorFromString(randomColor)]这是一个可怕的代码。使用Aaron的答案。如果你想使用基于文本的方法来调用类上某个键的值,请使用@moby的答案。他得到了你想要的。这个解决方案非常优越,因为你可以在数组中放置任何颜色。使用内置
UIColor
对象的字符串表示法非常简单ting。如果你想使用基于文本的方法调用类上某个键的值,请使用@moby的答案。他得到了你想要的。这个解决方案非常优越,因为你可以在数组中放置任何颜色。使用内置
UIColor
对象的字符串表示非常有限。