【问题标题】:Objective C get the old location in NSARRAY目标 C 获取 NSARRAY 中的旧位置
【发布时间】:2015-03-30 01:50:25
【问题描述】:
method - (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation

由于这种方法已被弃用,我想知道如何访问 NSArray 中的旧位置。 Array 是否存储每次更新的位置。我尝试了以下方法,但无法更新

- (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 );

}

【问题讨论】:

    标签: objective-c core-location


    【解决方案1】:

    locationManager:didUpdateLocations: 返回您尚未看到的位置列表。它可以将多个更新批处理到一个通知中。但它不会向您发送您已经收到的数据。如果您想跟踪以前收到的位置,则需要自己存储这些位置。

    【讨论】:

    • 我将如何跟踪?
    • 当位置进来时,存储它们。取决于您的数据模型和需求。在一个属性中,Core Data、NSUserDefaults、本地文件、你的服务器,无论你的产品使用什么来存储它的数据。
    • 我的问题是 oldLocation = [locations lastObject];只会不断更新位置,使其成为最新的而不是旧的
    • 对。您需要将oldLocation 永久存储在某处。您将其存储在哪里取决于您。系统不会向您发送任何旧的位置信息。如果需要,您可以自行存储它。看起来您将其存储在 NSUserDefaults 中。因此,如果您需要旧的位置信息,可以在存储之前从那里读取。
    【解决方案2】:

    我使用了一个我称之为 locHistory 的 NSMutableArray,如下所示:

    - (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
       [locHistory addObject:locationManager.location];
       if ([locHistory count] > 2) {
        [locHistory removeObjectAtIndex:0];
       }
    //more code...
    }
    

    由于某种原因,它不能与 [locations lastObject] 一起使用,因此我将 locationManager.location 添加到数组中。我用 initWithCapacity:2 在别处初始化 NSMutableArray,它可能是 1,因为它只会扩展它。每次更新位置时,我都会添加新位置并在元素数量超过 2 时删除第一个元素。之后剩下的是索引 0 处的旧位置和索引 1 处的最新位置。也许有更好的方法,但这对我有用。

    【讨论】:

      猜你喜欢
      • 2011-12-11
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      相关资源
      最近更新 更多