我花了几个小时试图解决这个问题,但我的想法已经用尽了。
我要做的就是归档一个对象,但方法archiveRootObject
一直在返回NO
这是我的代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"MyAppCache"];
NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:@"archive.data"];
if(![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSArray *array = [NSArray arrayWithObjects:@"hello", @"world", nil];
NSLog(@"Full Path: %@", fullPath);
BOOL res = [NSKeyedArchiver archiveRootObject:array toFile:fullPath];
if(res){
NSLog(@"YES");
}else{
NSLog(@"NO");
}
每次运行时,都会打印NO
。
任何帮助将不胜感激!
答案 0 :(得分:6)
使用路径fullPath
创建目录,然后尝试在同一路径中写入文件。用这样的文件覆盖目录是不可能的。使用cacheDirectory
字符串创建目录。
答案 1 :(得分:1)
NSString * cacheDirectory不是可变字符串,在您初始化之后,您尝试修改它,以便您写入顶级目录。
要快速解决问题,请尝试:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([documentPaths count] > 0) ? [documentPaths objectAtIndex:0] : nil;
NSString *documentsResourcesPath = [documentPath stringByAppendingPathComponent:@"MyAppCache"];
NSString *fullPath = [documentsResourcesPath stringByAppendingPathComponent:@"archive.data"];