我正在尝试显示用户位置和目标位置之间距离的应用程序。我打算获取用户位置 didUpdateToLocation 方法并存储在数组中。然后,将其放入表格视图委托“cellForRowAtIndexPath”中以计算距离并显示在表格单元格中。但是,它不起作用。请看我的代码如下。有人可以帮忙吗?
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
if (newLocation.horizontalAccuracy < 0) return;
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
if (currentLocation == nil || currentLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
self.currentLocation = newLocation;
// locationMeasurements is NSMutableArray to store currentLocation (CLLocation) information.
[locationMeasurements addObject:currentLocation];
[self.tableView reloadData];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
CLLocation *location = [locationMeasurements objectAtIndex:indexPath.row];
return cell;
}
它崩溃了,在控制台的数组中什么也没告诉我(见下文)。但是,我在 'didUpdateToLocation' 中 NSLog 这个数组,它可以正确显示它。
**** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'*
然后,我尝试 NSLog locationMeasurements (array) in cellForRowAtIndexPath
NSLog(@"locationMeasurements ===%@",[locationMeasurements description]);
它在几个语句中显示空白信息,然后显示正确的信息。见下文。
locationMeasurements ===(
)
locationMeasurements ===(
)
locationMeasurements ===(
)
locationMeasurements ===(
)
locationMeasurements ===(
"<+37.33233141,-122.03121860> +/- 5.00m (speed 0.00 mps / course -1.00) "
)
locationMeasurements ===(
"<+37.33233141,-122.03121860> +/- 5.00m (speed 0.00 mps / course -1.00) "
)
locationMeasurements ===(
"<+37.33233141,-122.03121860> +/- 5.00m (speed 0.00 mps / course -1.00) "
)
locationMeasurements ===(
"<+37.33233141,-122.03121860> +/- 5.00m (speed 0.00 mps / course -1.00) "
)
有人可以给我一些建议吗?我应该怎么办?
预先感谢。