我有点困惑为什么以下不起作用。谁能赐教一下?
我有一个返回 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/