method - (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
由于此方法已被弃用,我想知道如何访问 NSArray 中的旧位置。阵列是否存储每次更新的位置。我尝试了以下方法,但无法更新
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
CLLocation* location = [locations lastObject];
CLLocation *oldLocation;
NSNumber *lat = [NSNumber numberWithDouble:location.coordinate.latitude];
NSNumber *lon = [NSNumber numberWithDouble:location.coordinate.longitude];
[[NSUserDefaults standardUserDefaults] setInteger:counter forKey:@"counter"];
NSDictionary *userLocation=@{@"lat":lat,@"long":lon};
[defaults setObject:userLocation forKey:@"userLocation"];
[defaults synchronize];
if (locations.count > 1) {
oldLocation = locations[locations.count - 2];
}
NSLog(@"old location(%f,%f)", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude );
// NSLog(@"new location (%f,%f)", location.coordinate.latitude, location.coordinate.longitude );
}
>locationManager:didUpdateLocations:
返回您尚未看到的位置列表。它可以将多个更新批处理到单个通知中。但它不会向您发送已收到的数据。如果您想跟踪之前已经收到的位置,则需要自己存储这些位置。
我使用一个我称之为locHistory的NSMutableArray来做到这一点,如下所示:
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[locHistory addObject:locationManager.location];
if ([locHistory count] > 2) {
[locHistory removeObjectAtIndex:0];
}
//more code...
}
由于某种原因,它不适用于[location lastObject],所以我将locationManager.location添加到数组中。我在其他地方使用 initWithCapacity:2 初始化 NSMutableArray,这可能是 1,因为它只会扩展它。每次它更新位置时,我都会添加新位置并在元素数量超过 2 时删除第一个元素。在此之后剩下的是索引 0 处的旧位置和索引 1 处的最新位置。也许有更好的方法,但这对我有用。