如何在手机文档中的子文件夹(AnyName)中保存图像帮助我

时间:2011-04-28 21:19:39

标签: iphone ios-4.2

她在我的程序中使用这个编码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsPath = [paths objectAtIndex:0]; 
NSString *imageCacheDirPath = [docsPath stringByAppendingPathComponent:@"Image"];
NSString *imageCachePath = [imageCacheDirPath stringByAppendingPathComponent:@"1.jpg"]; 
[[NSFileManager defaultManager] createFileAtPath:imageCachePath contents:dataObj attributes:nil];

我的编码中出了什么问题。发现一些示例代码。

1 个答案:

答案 0 :(得分:10)

一个潜在的问题是,当您尝试在其中创建文件时,“Image”目录不存在 - createFileAtPath方法需要正确运行。因此,请检查Image文件夹是否存在,并根据需要创建它:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsPath = [paths objectAtIndex:0]; 
NSString *imageCacheDirPath = [docsPath stringByAppendingPathComponent:@"Image"];
NSString *imageCachePath = [imageCacheDirPath stringByAppendingPathComponent:@"1.jpg"]; 

if (![[NSFileManager defaultManager] fileExistsAtPath: imageCacheDirPath])
      [[NSFileManager defaultManager] createDirectoryAtPath:imageCacheDirPath 
                                withIntermediateDirectories:NO 
                                                 attributes:nil
                                                      error:NULL];

[[NSFileManager defaultManager] createFileAtPath:imageCachePath 
                                        contents:dataObj 
                                      attributes:nil];