2010-03-21 21 views
31

içinde depolanır Benim sorunum, objektif-c'deki bir enum aslında bir int değeri olduğu için, onu bir NSMutableArray içinde saklayamıyorum. Görünüşe göre NSMutableArray, int gibi herhangi bir c-veri tipini almayacaktır.Enum değerleri bir NSMutableArray

Bunu başarmanın ortak bir yolu var mı?

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

cevap

58

Wrap bir NSNumber içinde numaralama değeri dizideki koymadan önce: gibi

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

Ve almak Bu:

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

+1

Genellikle bu güvenli olmalı, ama çeteleler temsil edilebilir beri, olmadığında durumlar vardır dahili olarak farklı tiplerde. Bu yanıtı alternatif bir http://stackoverflow.com/questions/1187112/cocoa-dictionary-with-enum-keys/1187901#1187901 – DougW

+0

Güzel çözüm, teşekkürler –

2

Bir NSNumber nesnesine içine enum değerleri sarabilirsiniz:

[NSNumber numberWithInt:green]; 
9

Macatomy'nin cevabı doğru. Ama NSNumber yerine NSValue kullanmanızı öneririm. Hayattaki amacı budur.

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

ve:

17

Modern cevap gibi görünebilir

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

MyColors theGreenColor = ((NSInteger *) listesi [0]) .intValue; MyColors tarafından değiştirilemez theGreenColor = (MyColors) [liste [0] intValue]; – Haider

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

normalde doğru yolu olmalı NSNumber uysun diye. Bazı durumlarda NSString olarak bunları kullanmak için yararlı olabilir, böylece bu durumda bu kod satırını kullanabilirsiniz:

[@(MyEnum) stringValue];