Mundi Mundi - 4 months ago 20
iOS Question

Objective-C macro for class message

I have a dictionary with color settings and tried this:

#define ColorWithString( x) [UIColor #x]

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


I get an error
Expected identifier
.

I know there are some subtleties with string preprocessing. Maybe it is not even possible to send a dynamic message to a class. Any suggestions to make this work?

Answer

Take a look at what your macro expands to:

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

That’s obviously not legal Objective-C code. I think you could use performSelector: in combination with NSSelectorFromString:

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

…but why not do simply this?

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