所以,我有这样的定义:
typedef enum {
red = 1,
blue = 2,
white = 3
} car_colors;
然后,我有一个 car_colors 类型的变量:
car_colors myCar;
问题是,我在 NSString 中收到汽车的颜色。它必须是一个 NSString,我无法更改它。如何从 NSString 转换为 car_colors 类型?
NSString *value = [[NSString alloc] initWithString:@"1"];
myCar = [value intValue]; // <-- doesn't work
任何想法?
谢谢!
这是一个使用的实现NSDictionary
和现有的枚举
在.h文件中:
typedef NS_ENUM(NSInteger, City) {
Toronto = 0,
Vancouver = 1
};
@interface NSString (EnumParser)
- (City)cityEnumFromString;
@end
在 .m 文件中:
@implementation NSString (EnumParser)
- (City)cityEnumFromString{
NSDictionary<NSString*,NSNumber*> *cities = @{
@"Toronto": @(Toronto),
@"Vancouver": @(Vancouver),
};
return cities[self].integerValue;
}
@end
示例用法:
NSString *myCity = @"Vancouver";
City enumValue = [myCity cityEnumFromString];
NSLog(@"Expect 1, Actual %@", @(enumValue));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)