3

我花了过去几个小时试图弄清楚这一点,但我已经没有想法了。

我要做的就是归档一个对象,但该方法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.

任何帮助,将不胜感激!

4

2 回答 2

6

您使用该路径创建一个目录,fullPath然后尝试将文件写入同一路径。用这样的文件覆盖目录是不可能的。使用您的cacheDirectory字符串来创建您的目录。

于 2013-01-14T21:09:29.170 回答
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"];
于 2013-01-14T21:09:32.167 回答