ios - 如何使用 NSKeyedArchiver 存储 CLLocation 对象?

标签 ios cllocation nskeyedarchiver

我有点困惑为什么以下不起作用。谁能赐教一下?

我有一个返回 filePath 的函数:

- (NSString *) lastLocationPersistenceFilePath {
    NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"last_location"];
    return filePath;
}

然后,在一个由按钮触发的方法中,我尝试像这样保存一个 CLLocation 对象:

// Store this location so it can persist:
BOOL success = [NSKeyedArchiver archiveRootObject:_startLocation toFile:[self lastLocationPersistenceFilePath]];
if (!success) {
    NSLog(@"Could not persist location for some reason!");
} else {
    NSLog(@"New location has been stored.");
}

在我的 viewDidLoad: 中,我尝试加载它:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Retrieve last location:
    CLLocation *decodedLocation = [NSKeyedUnarchiver unarchiveObjectWithFile:[self lastLocationPersistenceFilePath]];

    if (decodedLocation) {
        _startLocation = decodedLocation;
    } else {
        NSLog(@"Decoding failed.");
    }
}

归档失败,这当然意味着我也无法解码任何内容。我觉得我遗漏了一些明显/微不足道的东西……有什么指示吗?

最佳答案

简单地说,无法写入应用程序的资源目录。而是写入应用程序的文档目录。

代码示例"

- (NSString *) lastLocationPersistenceFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths firstObject];
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"last_location"];
    return filePath;
}

关于ios - 如何使用 NSKeyedArchiver 存储 CLLocation 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648277/

相关文章:

objective-c - NSMutableArray 不断返回 null

ios - 如何在 uitableviewcell 内的 TextView 中显示来自 parse.com 的数组?

ios - 检查 CLPlacemark 的名称是否为街道地址

ios - NSKeyedUnarchiver 未返回 "nil"

arrays - 在设备上本地保存自定义类数组

cocoa - NSCoding 和 NSKeyedArchiving - "The document could not be loaded"

objective-c - 如何在 iOS 应用程序中创建 .doc 文件或文字处理器?

ios - 在 iOS 应用程序启动时请求日历和推送通知访问权限是否可以?

ios - 从 CLLocationManager 中过滤掉不良位置

iphone - iPhone 5 上的 CLLocationManager 标题问题