从NSString或typesNSString中删除@“”为variables名称

我从文件读取NSString,然后我想#定义这是一个UIColor,所以我可以快速改变颜色。

我想要这样工作:

#define GRAY [UIColor darkGrayColor] 

然后从文件中读取string:@“GRAY”,并将其放入名为kColor的NSStringvariables中

然后将其粘贴到backgroundcolor属性,如下所示:

 myController.view.backgroundColor = kColor; 

现在这意味着我得到:

 myController.view.backgroundColor = @"GRAY"; 

我需要:

 myController.view.backgroundColor = GRAY; 

为#define工作。 那么如何从string中删除@“”或将string转换为variables名? 我没有被困在#define,所以如果有另一种方式来使这个工作,我打开了。

非常感谢帮助。

你可以将颜色加载到NSDictionary

 // Put this in some global scope NSDictionary *colors = [NSDictionary dictionaryWithObjectsAndKeys: [UIColor darkGrayColor], @"GRAY", nil]; // using the dictionary myController.view.backgroundColor = [colors objectForKey:kColor]; 

当你说'从文件读取string:@“灰色”'你的意思是在应用程序运行时? 如果是这样,那么你不能使用编译时发生的#define(s)。

你不能这样做。 Objective-C是一种编译语言,所以你不能像使用一段代码那样使用NSString 。 您将需要一种方法来从文件中读取从string/ NSString中返回正确的颜色。

丹尼尔的回答可能是最好的。 由于他没有提供任何代码,这是一个实现:

 -(UIColor*) colorFromString: (NSString*) colorName { static NSDictionary colors = nil; if (colors == nil) { colors = [NSDictionary dictionaryWithObjectsAndKeys: [UIColor darkGreyColor], @"GRAY", [UIColor blueColor], @"BLUE", // etc nil]; [colors retain]; } return [colors objectForKey: colorName]; }