How to store enum values in a NSMutableArray

前端 未结 6 1193
故里飘歌
故里飘歌 2021-02-06 22:58

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

相关标签:
6条回答
  • 2021-02-06 23:12

    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 讨论(0)
  • 2021-02-06 23:14
    NSMutableArray *corners = [[NSMutableArray alloc] initWithObjects:
                               @(Right), 
                               @(Top), 
                               @(Left), 
                               @(Bottom), nil];
    Corner cornerType = [corner[0] intValue];
    
    0 讨论(0)
  • 2021-02-06 23:15

    You can wrap your enum values in a NSNumber object:

    [NSNumber numberWithInt:green];
    
    0 讨论(0)
  • 2021-02-06 23:20

    A modern answer might look like:

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

    and:

    MyColors theGreenColor = ((NSInteger*)list[0]).intValue;
    
    0 讨论(0)
  • 2021-02-06 23:26

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

    0 讨论(0)
  • 2021-02-06 23:33

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

    0 讨论(0)
提交回复
热议问题