2012-04-07 56 views
1

我正在閱讀一些json輸出...只是一些整數。第一個NSLog輸出完美的東西。在這種情況下,有3個元素。我不明白如何訪問我猜測的特定元素。從NSMutableArray中檢索「int」?

NSMutableArray *json = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

NSLog(@"json: %@ \n",json); 

int count = (int)[json objectAtIndex:0]; 
int count1 = (int)[json objectAtIndex:1]; 
int count2 = (int)[json objectAtIndex:2]; 
NSLog(@"count %i %i %i\n",count,count1,count2); 
+0

爲什麼如果id聲明瞭方法-intValue就會強制轉換爲int? – CodaFi 2012-04-07 23:54:13

回答

3

這可能是因爲這些都是NSNumbers。試試這個:

int count = [[json objectAtIndex:0] intValue]; 
int count1 = [[json objectAtIndex:1] intValue]; 
int count2 = [[json objectAtIndex:2] intValue]; 
NSLog(@"count %i %i %i\n",count,count1,count2); 
+0

就是這樣..謝謝。 – 2012-04-07 23:56:47

3

NSArray包含一個對象,你不應該將其轉換爲int,這是不行的。查看您的代碼並確定NSJSONSerialization的輸出。如果它是一個整數,它通常是的NSNumber一個實例,因此嘗試:

int count = [[json objectAtIndex:0] intValue]; 
2

NSArrayNSMutableArray不能使用int S和其他非ID對象作爲鍵或值,所以劇組不會去上班。最有可能的值是NSNumber類型的,所以你需要調用intValue他們:

int count = [[json objectAtIndex:0] intValue]; 
int count1 = [[json objectAtIndex:1] intValue]; 
int count2 = [[json objectAtIndex:2] intValue];