防止索引越界

时间:2013-10-08 14:48:37

标签: ios xcode

如果我有值,我只能执行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 个答案:

答案 0 :(得分:1)

在获取对象之前检查值:

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

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