编辑:帖子末尾的解决方案
我在创建 NSCachesDirectory 的子目录并向其添加 NSData 对象时遇到问题。我已经提到了与此相关的多个 SO 帖子,但是当我调试代码时,它告诉我文件夹中的 NSData 文件不存在。我的代码:
NSURL *photoURL = [FlickrFetcher urlForPhoto:self.singlePhotoDictionary
format:FlickrPhotoFormatLarge];
NSData *URLToData = [NSData dataWithContentsOfURL:photoURL];
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newDirectory = [cacheDirectory stringByAppendingPathComponent:@"Photos"];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:newDirectory isDirectory:&isDir] && isDir == NO)
{
[[NSFileManager defaultManager]createDirectoryAtPath:newDirectory withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [newDirectory stringByAppendingPathComponent:@"thePhotos.jpg"];
NSLog(@"%@", filePath);
//[URLToData writeToFile:filePath atomically:NO];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:URLToData attributes:nil];
NSData *theData = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSArray *contentsInManager = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:newDirectory error:nil];
theData 和 contentsInManager 原来是:
theData NSData * 0x00000000
contentsInManager NSArray * 0x00000000
这里有什么帮助吗?子目录存在,但不会在其中创建文件。
作为一个附带问题:我们什么时候需要创建自己的 NSFileManager 实例而不是使用 defaultManager?
提前致谢!
解决方案:经过反复试验,我尝试删除子目录并重新创建它。一旦我这样做了,该文件就可以写入子目录。