NSArray objectAtIndex索引0超出空数组的边界 [英] NSArray objectAtIndex index 0 beyond bounds for empty array

查看:285
本文介绍了NSArray objectAtIndex索引0超出空数组的边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理别人的应用程序而且我收到此错误:

I'm working on someone else's app and and I'm getting this error:

'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 
 beyond bounds for empty array'

Xcode指向这一行:

Xcode points to this line:

 NSDictionary *geo = [response[0] objectForKey:@"geometry"];

以下是完整方法:

- (void)loadLatLong {

indx ++;
if (indx == [datalist count]) {
    [self showMarker];
//        self.alertView.hidden = true;
//        [self setThreeQuarters];
    [self.progressbar setProgress:1.0 animated:YES];
    return;
}
PointClass *pt = datalist[indx];
NSString *stPt = [pt.Location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *str = [stPt stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *url = [NSString stringWithFormat:@"https://maps.google.com/maps/api/geocode/json?address=%@&sensor=false&key=AIzaSyAoSBH8mBmeVp2HVx6vJrkTvl3bjRFiWag",str];

NSURL *urlString = [NSURL URLWithString:url];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
[manager GET:[urlString absoluteString ]parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSArray *response = [responseObject objectForKey:@"results"];
    NSDictionary *geo = [response[0] objectForKey:@"geometry"];
    NSDictionary *location = [geo objectForKey:@"location"];

    pt.lat = [[location objectForKey:@"lat"] doubleValue];
    pt.lng = [[location objectForKey:@"lng"] doubleValue];
    datalist[indx] = pt;
    NSLog([NSString stringWithFormat:@"%%d \n"], indx);
    [self loadLatLong];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

  }];
}

无法找出更改代码的位置。

Can't figure out where to change the code.

更新:
我想补充一点,它有时只会崩溃,有时会加载

UPDATE: I want to add that it only crashes sometimes and sometimes it loads

推荐答案

代码假设响应数组总是至少有一个元素。当数组为空时,这会中断,因此您需要添加代码来检查它:

The code makes an assumption that response array always has at least one element. This breaks when the array is empty, so you need to add code to check for it:

NSArray *response = [responseObject objectForKey:@"results"];
if (response.count == 0) {
    // Continue loading more data:
    [self loadLatLong];
    return;
}
NSDictionary *geo = [response[0] objectForKey:@"geometry"];

这篇关于NSArray objectAtIndex索引0超出空数组的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆