2009-05-29 70 views
23

所以,我有這樣的定義:的Objective-C:的NSString枚舉

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 

有什麼想法嗎? 謝謝!

+0

究竟不起作用?在要將字符串轉換爲整數的方法中放置一個斷點,您應該能夠確切地看到哪個部分會發生故障。 – 2009-05-29 14:24:03

回答

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

Enum有不同的含義,我們不能用NSArray或NSDictionary替換枚舉。開發庫時,您必須使用適當的數據類型。這不是一個最佳的解決方案。 – 2011-11-02 12:51:14

+5

@AntoBinishKaspar問題不是關於一個圖書館,而是關於解決特定問題的一個特定約束。誰說你不能用字典取代枚舉?我不是在談論替代品的下降,而是在談論解決方案的另一種方式。 – Abizern 2012-01-05 16:05:47

7

您也可以將值放入數組中。

NSArray *carColorsArray = @[@"red", @"blue", @"white"]; 

然後,您可以使用indexOfObject獲取特定字符串的索引。

car_colors carColor = [carColorsArray indexOfObject:@"blue"] + 1; 
-6

我找到了解決辦法:

if ([car_color isEqualToString:@"1"]) 
     return red; 
if ([tipo_pdi isEqualToString:@"2"]) 
     return blue; 
if ([tipo_pdi isEqualToString:@"3"]) 
     return white; 

但我不喜歡這樣的「如果」的風格,如果我有什麼千個色?沒有更自動的解決方案嗎?

+4

字典 - 正如我在我的回答中所說的。 – Abizern 2009-05-29 15:12:21

46

這裏使用NSDictionary現有枚舉

在.h文件中的實現和:在.m文件

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

@interface NSString (EnumParser) 
- (City)cityEnumFromString; 
@end 

@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)); 
3

這裏有很多很好的答案:Converting between C enum and XML

它們基本上和Abizern的一樣,但是如果你的應用程序對字符串到枚舉的轉換有很大的幫助,它們會更簡潔一些。有一些解決方案將字符串和枚舉定義保持在一起,並使轉換成爲單一,易於閱讀的代碼行。

1
// ... 
typedef enum { 
    One = 0, 
    Two, 
    Three 
} GFN; 
// ... 
#define kGFNPrefix @"GFNEnum_" 
// ... 
+ (NSString *)gfnToStr:(GFN)gfn { 
    return [NSString stringWithFormat:@"%@%d", kGFNPrefix, gfn]; 
} 

+ (GFN)gfnFromStr:(NSString *)str { 
    NSString *gfnStr = [str stringByReplacingOccurrencesOfString:kGFNPrefix withString:@""]; 
    return [gfnStr intValue]; 
} 
// ... 

我的選擇=)