开发者

How to store enum values in a NSMutableArray

开发者 https://www.devze.com 2022-12-23 10:17 出处:网络
My problem is since an enum in objective-c essentially is an int value, I am not able to store it in a NSMutableArray. Apparently NSMutableArray won\'t take any c-data types like an int.

My problem is since an enum in objective-c essentially is an int value, I am not able to store it in a NSMutableArray. Apparently NSMutableArray won't take any c-data types like an int.

Is there any common way to achieve this ?

typedef enum 
{
    g开发者_Python百科reen,
    blue,
    red

} MyColors;


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

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


Wrap the enum value in an NSNumber before putting it in the array:

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

And retrieve it like this:

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


A modern answer might look like:

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

and:

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


Macatomy's answer is correct. But instead of NSNumber I would suggest you use NSValue. That is its purpose in life.


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


You can wrap your enum values in a NSNumber object:

[NSNumber numberWithInt:green];


To go with NSNumber should be the right way normally. In some cases it can be useful to use them as NSString so in this case you could use this line of code:

[@(MyEnum) stringValue];
0

精彩评论

暂无评论...
验证码 换一张
取 消