我在我的app中的异步线程上调用了Google的地理编码API和Distance Matrix API。但是它发出了NSRangeException。 这是我的代码:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^
{
NSString *urlStringGeoCoding;
NSString *urlString;
urlStringGeoCoding = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/"
@"api/geocode/json?"
@"latlng=40.714224,-73.961452&sensor=true"];
urlString = [NSString stringWithFormat:@"http://maps.googleapis.com"
@"/maps/api/distancematrix/json?"
@"origins=%@&destinations=%@&mode=driving&"
@"language=en&sensor=true&units=imperial","
@"current,@"Chicago,IL"];
NSURL *urlGeo = [NSURL URLWithString:[urlStringGeoCoding
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:[urlString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *googledatageo = [NSData dataWithContentsOfURL:urlGeo];
NSData *googledata = [NSData dataWithContentsOfURL:url];
NSError *errorgeo;
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:googledata
options:kNilOptions
error:&error];
NSMutableDictionary *jsongeo = [NSJSONSerialization JSONObjectWithData:googledatageo
options:kNilOptions
error:&errorgeo];
NSString *result = [[[[[[json objectForKey:@"rows"] objectAtIndex: 0] objectForKey:@"elements"] objectAtIndex:0]objectForKey:@"distance"]objectForKey:@"text"];
if(jsongeo)
{
NSString *resultgeo = [[[jsongeo objectForKey:@"results"] objectAtIndex: 0] objectForKey:@"formatted_address"] ;
}
dispatch_sync(dispatch_get_main_queue(), ^
{
cell.distanceLabel.text = result;
});
});
这是我得到的错误: 由于未捕获的异常终止应用程序' NSRangeException',原因:' * - [__ NSArrayI objectAtIndex:]:索引0超出空数组的范围' * 第一次抛出调用堆栈: (0x289a012 0x2210e7e 0x284fb44 0x1318c 0x57f953f 0x580b014 0x57fc2e8 0x57fc450 0x9112ae72 0x91112d2a)
如何在此处阻止范围异常?
答案 0 :(得分:1)
通过检查count
,"rows"
和"elements"
数组的"results"
,您可以在调用objectAtIndex:
之前阻止这些范围异常。
分解result
和resultgeo
这两条非常长的行是个好主意;只需使用一些临时的NSArray
变量。