2013-10-08 41 views
0

如果我有值存在,那麼我只能執行objectAtIndex時遇到問題。防止索引超出範圍

我的代碼:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
NSDictionary *results = [json objectForKey:@"d"]; 

NSString *error = [results objectForKey:@"error"]; 
NSLog(@"results::%@", [results objectForKey:@"agency"]); 
if (results !=nil) 
{ 
    item = [[results objectForKey:@"agency"] objectAtIndex:0]; 
    codeItem = [[results objectForKey:@"agency"] objectAtIndex:1]; 
} 

它工作正常,如果我有數據的JSON但如果JSON回來這樣的:

{"d":{"success":true,"agency":[]}} 

它崩潰了,我知道我的if語句是錯誤的但我不知道做這個工作的正確方法。

回答

1

獲取對象之前就檢查值:

NSArray *agencyItem = [results objectForKey:@"agency"]; 

if ([agencyItem count] > 1) 
{ 
    codeItem = [agencyItem objectAtIndex:1]; 
} 
+0

'agencyItem = nil'是多餘的。 – Kevin

+0

我加了!= nil,只是因爲我不確定輸出是否被刪除。 –

+2

只要記住'[somearray firstObject]'和'[somearray lastObject]'總是可以安全使用;如果'somearray'爲空,那麼這兩個方法返回'nil'。 –