2010-03-21 56 views
31

我的问题是因为在Objective-c中的枚举本质上是一个int值,我不能将它存储在NSMutableArray中。显然NSMutableArray不会像int那样采用任何c数据类型。如何将枚举值存储在NSMutableArray中

是否有任何常见的方法来实现这一目标?

typedef enum 
{ 
    green, 
    blue, 
    red 

} MyColors; 


NSMutableArray *list = [[NSMutableArray alloc] initWithObjects: 
          green, 
          blue, 
          red, 
          nil]; 

//Get enum value back out 
MyColors greenColor = [list objectAtIndex:0]; 

回答

58

裹在一个NSNumber枚举值把它在数组中前:

NSNumber *greenColor = [NSNumber numberWithInt:green]; 
NSNumber *redColor = [NSNumber numberWithInt:red]; 
NSNumber *blueColor = [NSNumber numberWithInt:blue]; 
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects: 
          greenColor, 
          blueColor, 
          redColor, 
          nil]; 

和检索它像此:

MyColors theGreenColor = [[list objectAtIndex:0] intValue];

+1

一般来说,这应该是安全的,但有些时候它不是,因为枚举可表示内部为各种不同的类型。看到这个答案替代http://stackoverflow.com/questions/1187112/cocoa-dictionary-with-enum-keys/1187901#1187901 – DougW 2011-07-20 18:11:36

+0

好的解决方案,谢谢 – 2017-08-10 13:20:02

2

您可以在一个NSNumber的对象换你枚举值:

[NSNumber numberWithInt:green]; 
9

Macatomy的回答是正确的。但是,而不是NSNumber,我会建议你使用NSValue。这是它的人生目标。

17

现代的回答可能是:

NSMutableArray *list = 
[NSMutableArray arrayWithArray:@[@(green), @(red), @(blue)]]; 

和:

MyColors theGreenColor = ((NSInteger*)list[0]).intValue; 
+1

MyColors theGreenColor =((NSInteger *)list [0]) .intValue; 可替换为 MyColors theGreenColor =(MyColors)[list [0] intValue]; – Haider 2016-01-30 07:49:49

7
NSMutableArray *corners = [[NSMutableArray alloc] initWithObjects: 
          @(Right), 
          @(Top), 
          @(Left), 
          @(Bottom), nil]; 
Corner cornerType = [corner[0] intValue]; 
0

要与NSNumber去应该是正常的正确途径。在某些情况下,它可以将它们作为NSString有用的,在这种情况下,你可以使用此行代码:

[@(MyEnum) stringValue];