Array of enums - convert to NSArray

后端 未结 3 804
清酒与你
清酒与你 2021-01-17 12:32

Having

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

Or

typedef enum {MyA, MyB, Null} myEnum;

1) How do

相关标签:
3条回答
  • 2021-01-17 13:04

    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).

    0 讨论(0)
  • 2021-01-17 13:06

    In Obj C:

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

    In Swift:

    enumArray = NSArray(objects: enum1.rawValue, enum2.rawValue);
    
    0 讨论(0)
  • 2021-01-17 13:07

    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];
    
    0 讨论(0)
提交回复
热议问题