【问题标题】:Managing files and directories in an app's Documents directory在应用的 Documents 目录中管理文件和目录
【发布时间】:2013-11-27 05:23:08
【问题描述】:

我正在尝试研究如何管理我应用的 Documents 文件夹中的文件和目录。我一直试图理解 NSData 类,但没有喜悦。我已经设法使用以下代码将图像写入我的 Documents 文件夹。

- (IBAction)writeImage:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];

UIImage *image = [UIImage imageNamed:@"Default.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}

我想知道的是如何创建和删除目录和文件。谁能指出我正确的地方看?提前致谢。

【问题讨论】:

  • 是的,NSFileManager

标签: ios objective-c nsdocumentdirectory


【解决方案1】:

您可以使用的文件夹:

 [[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];

它将在给定路径创建所有文件夹,这很酷:)

【讨论】:

    【解决方案2】:

    NSFileManager 类使您能够执行许多通用文件系统操作,并将应用与底层文件系统隔离开来。

    NSFileManager 类中有一个名为+defaultManager 的类方法,它始终为您提供相同的FileManager 对象或共享对象,并且可以使用此共享文件管理器对象执行大多数文件操作。

    【讨论】:

      【解决方案3】:

      如果文件已经存在,您可以通过避免覆盖来写入,如下所示,还可以检查文件夹是否可写。

      NSString *imageName = @"Default.png";
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectoryPath = [paths objectAtIndex:0];
      NSString *savedImagePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, imageName];
      
      // Write only if file does not exist.
      if (![[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
          NSData *imageData = UIImagePNGRepresentation(image);
          [imageData writeToFile:savedImagePath atomically:NO];
      }
      
      
      // Check if folder is writable
      NSString *folderPath = @"someFolderPath";
      if ([[NSFileManager defaultManager] isWritableFileAtPath:folderPath]) {
          NSLog(@"Folder is writable");
      }else {
          NSLog(@"Folder is not writable");
      }
      

      【讨论】:

        猜你喜欢
        • 2012-11-02
        • 2011-09-23
        • 1970-01-01
        • 2015-08-22
        • 1970-01-01
        • 2010-10-31
        • 2015-10-17
        • 2013-10-11
        • 1970-01-01
        相关资源
        最近更新 更多