我正在处理其他人的应用,并且我收到了此错误:
'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0
beyond bounds for empty array'
Xcode指向这一行:
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) {
}];
}
无法找出更改代码的位置。
更新: 我想补充一点,它有时只会崩溃,有时会加载
答案 0 :(得分:7)
代码假设response
数组总是至少有一个元素。当数组为空时,这会中断,因此您需要添加代码来检查它:
NSArray *response = [responseObject objectForKey:@"results"];
if (response.count == 0) {
// Continue loading more data:
[self loadLatLong];
return;
}
NSDictionary *geo = [response[0] objectForKey:@"geometry"];
答案 1 :(得分:1)
由于response
没有任何对象,因此崩溃了。您应该在致电response[0]
之前进行检查。像这样if ([response count] == 0) return;