【问题标题】:How can I save CLLocation better?如何更好地保存 CLLocation?
【发布时间】:2014-10-18 07:20:42
【问题描述】:

我正在尝试保存我的 CLLocation 位置以供将来在我的应用程序中使用。我想出了以下几点:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"/Locations.plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

[data setValue:[NSKeyedArchiver archivedDataWithRootObject:location] forKey:@"LocationList"];
[data writeToFile:path atomically:YES];

NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData: (NSData *)[data objectForKey:@"LocationList"]]];
    NSLog(@"%@",array);

当我运行我的应用程序时,编译器返回

-[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

我做错了什么?还是有更好的标准方法来保存 CLLocation 数据?

【问题讨论】:

  • 你不想专门使用 NSKeyedArchiver 吗?还是使用 CoreData 有意义?你的用例是什么?

标签: ios core-location cllocation nskeyedarchiver nskeyedunarchiver


【解决方案1】:

您已经忘记了您的方法实际返回的内容,当您将多个消息调用相互嵌入时,这是一种风险。

您存储了一个 CLLocation,所以这将返回一个 CLLocationObject:

[NSKeyedUnarchiver unarchiveObjectWithData: (NSData *)[data objectForKey:@"LocationList"]]

您的代码将其视为返回一个数组:

NSMutableArray *array = [[NSMutableArray alloc] initWithArray:... // Your returned CLLocation here.

这就是数组为 NULL 的原因。至于如何存储CLLocation数据,编码方式是正确的。 (见this answer for a clear reference to storing CLLocations as NSData objects。)

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2020-06-09
    相关资源
    最近更新 更多