gpt4 book ai didi

iphone - 如何在 NSMutableArray 中存储枚举值

转载 作者:太空狗 更新时间:2023-10-30 03:08:42 24 4
gpt4 key购买 nike

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

有什么通用的方法可以实现吗?

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

最佳答案

在将枚举值放入数组之前将其包装在 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];

关于iphone - 如何在 NSMutableArray 中存储枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2487587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com