Objective-c:NSString枚举 [英] Objective-c: NSString to enum

查看:111
本文介绍了Objective-c:NSString枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个定义:

  typedef枚举{
red = 1,
blue = 2,
white = 3
} car_colors;

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

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

  NSString * value = [[NSString alloc] initWithString:@1] ; 
myCar = [value intValue]; //< - 不工作

任何想法?
谢谢!

解决方案

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

  NSDictionary * carColourDictionary = @ {@Red:@ 1,
@ 蓝:@ 2,
@白:@ 3};

//使用字典获取数字
//假设您有一个方法可以将字符颜色返回为一个字符串:
// - (NSString *)colourAsString;
int carColour = carColourDictionary [object colourAsString];


So, I've got this definition:

typedef enum {
    red = 1,
    blue = 2,
    white = 3
} car_colors;

Then, I've got a variable of type car_colors: car_colors myCar;

The question is, I receive the color of the car in a NSString. It must be a NSString, I can't change that. How can I convert from NSString to car_colors type?

NSString *value = [[NSString alloc] initWithString:@"1"];
myCar = [value intValue]; // <-- doesn't work

any idea? thanks!

解决方案

Rather than use an array, why not use a dictionary; You have the colour NSString as keys, and you return whatever NSNumber you want. Something like; (Long winded for clarity).

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];

这篇关于Objective-c:NSString枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆