类消息的Objective-C宏

时间:2012-11-01 08:36:01

标签: ios objective-c cocoa c-preprocessor

我有一个带有颜色设置的字典并试过这个:

#define ColorWithString( x) [UIColor #x]

NSDictionary *settings = @{@"color" : @"whiteColor"};
UIColor *color = ColorWithString(settings[@"color"]);

我收到错误Expected identifier

我知道字符串预处理有一些细微之处。也许甚至不可能向类发送动态消息。有什么建议使这项工作?

2 个答案:

答案 0 :(得分:4)

看看你的宏扩展到了什么:

UIColor *color = [UIColor settings[@"color"]];

这显然不是合法的Objective-C代码。我认为您可以将performSelector:NSSelectorFromString结合使用:

UIColor *color = [UIColor performSelector:
    NSSelectorFromString(settings[@"color"])];

......但为什么不这样做呢?

NSDictionary *colors = @{
    @"white" : [UIColor whiteColor],
    @"red"   : [UIColor redColor]
};

答案 1 :(得分:2)

将宏更改为

#define ColorWithString( x) [UIColor performSelector:NSSelectorFromString(x)]

然后你可以使用宏作为

        NSDictionary *settings = @{@"color" : @"greenColor"};        
        UIColor *color = ColorWithString(settings[@"color"]);

CGColorRef

获取UIColor
CGColorRef colorRef = color.CGColor;