【问题标题】:Not able to create files in caches directory无法在缓存目录中创建文件
【发布时间】:2025-12-27 06:20:11
【问题描述】:

我正在尝试设置缓存目录以在我的应用程序中使用,但由于我不知道的原因未创建文件。我究竟做错了什么?以下是我正在使用的方法:

在类实用程序中:

+(NSString *)imageCachePath {
   NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
   NSString *pieceImagesDirectory = [cacheDirectory stringByAppendingPathComponent:@"PieceImages"];
   NSLog(@"imageCachPath is %@",pieceImagesDirectory);
   return pieceImagesDirectory;
}
+ (void)cacheImage:(UIImage *)image usingName:(NSString *)name;
{
   NSLog(@"Caching image %@",name);
   NSString *pieceImagesDirectory = [self imageCachePath];
   BOOL isDir = NO;
   NSError *error;
   if (! [[NSFileManager defaultManager] fileExistsAtPath:pieceImagesDirectory isDirectory:&isDir] && isDir == NO) {
      [[NSFileManager defaultManager]createDirectoryAtPath:pieceImagesDirectory withIntermediateDirectories:YES attributes:nil error:&error];
      NSLog(@"Error after creating directory:\n%@",error);
   } else {
      // file exists - I don't expect to use the else block. This is for figuring out what's going on.
      NSLog(@"File %@ exists -- is it a directory? %@",pieceImagesDirectory, isDir?@"YES":@"NO");
   }
   NSString *nameToUseInFilename = [name stringByReplacingOccurrencesOfString:@" " withString:@"_"];
   NSString *fullPath = [pieceImagesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",nameToUseInFilename]];
   NSData *data = UIImagePNGRepresentation(image);
   NSFileManager *fileManager = [NSFileManager defaultManager];
   //Save the file, overwrite existing if exists.
   NSLog(@"Attempting to create file at path %@ with %d bytes of data",fullPath, [data length]);
   if ([fileManager createFileAtPath:fullPath contents:data attributes:nil]) {
      NSLog(@"Success");
   } else {
      NSLog(@"Error creating file");
   }
}

在创建图像的类中,我这样调用方法:

// image is an object of type UIImage
// cachedImageName is a string that resolves to something like User Image/12
[Utilities cacheImage:image usingName:cachedImageName];

以下是调试器中的示例 NSLog 输出行:

... Caching image User Image/12
... imageCachPath is /var/mobile/Applications/5EBB1152-5CC1-4A30-ABD5-B4C9A60E4CB4/Library/Caches/PieceImages
... File /var/mobile/Applications/5EBB1152-5CC1-4A30-ABD5-B4C9A60E4CB4/Library/Caches/PieceImages exists -- is it a directory? YES
... Attempting to create file at path /var/mobile/Applications/5EBB1152-5CC1-4A30-ABD5-B4C9A60E4CB4/Library/Caches/PieceImages/User_Image/12.png with 12071 bytes of data
... Error creating file

【问题讨论】:

  • 您已经验证了PieceImages 存在并且是一个目录,但是您是否也验证了User_Image 存在并且是一个目录?

标签: ios nsfilemanager


【解决方案1】:

如果目录不存在,对NSFileManager fileExistsAtPath:isDirectory: 的调用会为您提供isDir 的不确定值。您应该将代码更改为:

BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:pieceImagesDirectory isDirectory:&isDir]) {
    [[NSFileManager defaultManager]createDirectoryAtPath:pieceImagesDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    NSLog(@"Error after creating directory:\n%@",error);
} else {
    // file exists - I don't expect to use the else block. This is for figuring out what's going on.
    NSLog(@"File %@ exists -- is it a directory? %@",pieceImagesDirectory, isDir?@"YES":@"NO");
}

您似乎还向路径添加了第二个文件夹User_Image。你永远不会创建这个目录。

我还建议您更改写入图像数据的方式。不要使用NSFileManager createFileAtPath:contents:attributes:,而是使用NSData writeToFile:options:error:。然后你可以得到一个错误对象,提供任何问题的更多细节。

最后,最好构建文件的完整路径。剥离最后一个路径组件(实际文件名),然后检查剩余路径是否存在。然后拨打createDirectoryAtPath... 并让它创建所有所有需要的文件夹。

【讨论】:

  • 你对那个 UserImage 是正确的。出于某种原因,我认为 withIntermediateDirectories:YES 正在应用于它,但当然,它仅适用于当时正在创建的目录。我敢打赌这就是问题所在。我将检查 NSData writeToFile:options:error:。我以前从未使用过。谢谢。
  • 是的。从 / 切换到 .在文件名中解决了问题——不是我想使用那个结构,但它确认没有创建目录是问题。