Objective-c:NSString到枚举

Hec*_*ret 25 cocoa enums objective-c

所以,我有这个定义:

typedef enum {
    red = 1,
    blue = 2,
    white = 3
} car_colors;
Run Code Online (Sandbox Code Playgroud)

然后,我有一个car_colors类型的变量:car_colors myCar;

问题是,我收到了NSString中汽车的颜色.它必须是NSString,我不能改变它.如何从NSString转换为car_colors类型?

NSString *value = [[NSString alloc] initWithString:@"1"];
myCar = [value intValue]; // <-- doesn't work
Run Code Online (Sandbox Code Playgroud)

任何的想法?谢谢!

小智 52

这是使用NSDictionary和现有枚举的实现

在.h文件中:

typedef NS_ENUM(NSInteger, City) {
    Toronto         = 0,
    Vancouver       = 1
 };

@interface NSString (EnumParser)
- (City)cityEnumFromString;
@end
Run Code Online (Sandbox Code Playgroud)

在.m文件中:

@implementation NSString (EnumParser)

- (City)cityEnumFromString{
    NSDictionary<NSString*,NSNumber*> *cities = @{
                            @"Toronto": @(Toronto),
                            @"Vancouver": @(Vancouver),
                            };
    return cities[self].integerValue;
}

@end
Run Code Online (Sandbox Code Playgroud)

样品用量:

NSString *myCity = @"Vancouver";
City enumValue = [myCity cityEnumFromString];

NSLog(@"Expect 1, Actual %@", @(enumValue));
Run Code Online (Sandbox Code Playgroud)


Abi*_*ern 18

而不是使用数组,为什么不使用字典; 你有颜色NSString作为键,你返回任何你想要的NSNumber.就像是; (为了清晰而啰嗦).

NSDictionary *carColourDictionary = @{@"Red": @1,
                                      @"Blue": @2,
                                      @"White": @3};

// Use the dictionary to get the number
// Assume you have a method that returns the car colour as a string:
// - (NSString *)colourAsString;
int carColour = carColourDictionary[object colourAsString];
Run Code Online (Sandbox Code Playgroud)

  • @AntoBinishKaspar问题不是关于一个库,而是围绕一个特定约束的特定问题.谁说你不能用字典取代枚举?我不是在谈论替代品,我正在谈论一种不同的解决方案. (5认同)

Tom*_*rys 8

您还可以将值放在数组中.

NSArray *carColorsArray = @[@"red", @"blue", @"white"];
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用indexOfObject获取特定字符串的索引.

car_colors carColor = [carColorsArray indexOfObject:@"blue"] + 1;
Run Code Online (Sandbox Code Playgroud)