Array of enums - convert to NSArray

心不动则不痛 提交于 2020-01-11 08:11:12

问题


Having

enum {MyA, MyB, Null};
typedef NSNumber myEnum;

Or

typedef enum {MyA, MyB, Null} myEnum;

1) How do I create an array

myEnum* myEnumTemp[] = {MyA, MyB};

Just gives "Implicit conversion of 'int' to NSNumber* is disallowed with ARC(ref. counting)

2) If you are able to create an array how to convert it to NSArray?


回答1:


Try to do it this way :

typedef enum { MyA, MyB, Null } myEnum;

Then, to create an array, wrap the numbers into NSNumbers objects :

NSArray *a = [NSArray arrayWithObjects:[NSNumber numberWithInteger:MyA],
                                       [NSNumber numberWithInteger:MyB],
                                       nil];



回答2:


In Obj C:

enumArray = @[@(enum1),@(enum2)];

In Swift:

enumArray = NSArray(objects: enum1.rawValue, enum2.rawValue);



回答3:


Basically, you need to wrap the value in a NSNumber object.

#define INT_OBJ(x) [NSNumber numberWithInt:x]

[array addObject:INT_OBJ(MyA)];

And there was nothing wrong with your other array, you just should have defined it like this:

typedef enum {MyA, MyB, Null} myEnum;

myEnum values[] = { MyA, MyB };

The problem was that you defined myEnum as a NSNumber, which is not equal to an enum value (int).



来源:https://stackoverflow.com/questions/8941821/array-of-enums-convert-to-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!