我有点困惑,为什么以下不起作用。有人可以开导我吗?
我有一个函数返回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.");
}
}
归档失败,当然,这意味着我也无法解码任何内容。我觉得我错过了一些明显/微不足道的东西......任何指针?
答案 0 :(得分:3)
简单地说,无法写入应用程序的资源目录。而是写入应用程序的文档目录。
代码示例“
- (NSString *) lastLocationPersistenceFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths firstObject];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"last_location"];
return filePath;
}