简体   繁体   English

管理应用程序的Documents目录中的文件和目录

[英]Managing files and directories in an app's Documents directory

I am trying to work out how to manage files and directories in my app's Documents folder. 我试图找出如何管理我的应用程序的文档文件夹中的文件和目录。 I have been trying to make sense of the NSData class but without joy. 我一直试图理解NSData类,但没有快乐。 I have managed to write an image to my Documents folder using the following code. 我已设法使用以下代码将图像写入我的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];
}

What I would like to know is how to create and delete directories and files. 我想知道的是如何创建和删除目录和文件。 Can anyone point me to correct place to look? 有谁能指出我正确的地方看? Thanks in advance. 提前致谢。

For folder you can use: 对于文件夹,您可以使用:

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

It will create all folders at given path which is cool :) 它将在给定路径创建所有文件夹,这很酷:)

The NSFileManager class enables you to perform many generic file-system operations and insulates an app from the underlying file system. NSFileManager类使您可以执行许多通用文件系统操作,并将应用程序与基础文件系统隔离。

There is a class method in NSFileManager class called +defaultManager which always gives you same FileManager object or shared Object and most file operations can be performed using this shared file manager object. NSFileManager类中有一个名为+defaultManager的类方法,它总是为您提供相同的FileManager对象或共享对象,并且可以使用此共享文件管理器对象执行大多数文件操作。

You can write by avoiding overwriting your file if it already exists as below and can also check if the folder is writable or not. 您可以通过避免覆盖文件来编写(如果文件已经存在,如下所示),还可以检查文件夹是否可写。

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM