如何在NSMutableArray中存储枚举值

Oys*_*sio 33 iphone cocoa objective-c

我的问题是因为objective-c中的枚举本质上是一个int值,我无法将其存储在一个NSMutableArray.显然NSMutableArray不会采用像int这样的任何c数据类型.

有没有什么常见的方法来实现这一目标?

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];
Run Code Online (Sandbox Code Playgroud)

ind*_*gie 62

在将枚举值放入数组之前将其包装在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];
Run Code Online (Sandbox Code Playgroud)

并检索它像这样:

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


Pat*_*Pat 20

现代答案可能如下:

NSMutableArray *list = 
 [NSMutableArray arrayWithArray:@[@(green), @(red), @(blue)]];
Run Code Online (Sandbox Code Playgroud)

和:

MyColors theGreenColor = ((NSInteger*)list[0]).intValue;
Run Code Online (Sandbox Code Playgroud)

  • MyColors theGreenColor = ((NSInteger*)list[0]).intValue; 可以换成 MyColors theGreenColor = (MyColors)[list[0] intValue]; (2认同)

nic*_*mro 10

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


Tai*_* Le 7

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