在iOS的文档文件夹中创建多个目录

App*_*ram 3 iphone directory ios nsdocumentdirectory

我想制作多个目录,我不知道如何.这是我的代码到现在为止.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"tops",@"bottoms",@"right" ];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder

}
Run Code Online (Sandbox Code Playgroud)

我希望有4个目录名为tops bottomoms left and left但是如果我以上述方式执行它就不起作用..有没有办法使用这个代码创建多个目录?还是我的代码错了?谢谢!

Din*_*aja 8

试试这个代码.

按要求创建目录.

NSArray *directoryNames = [NSArray arrayWithObjects:@"tops",@"bottoms",@"right",@"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

for (int i = 0; i < [directoryNames count] ; i++) {
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
}
Run Code Online (Sandbox Code Playgroud)

在应用程序的任何位置使用创建的目录.

NSArray *directoryNames = [NSArray arrayWithObjects:@"tops",@"bottoms",@"right",@"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

// This will return the folder name in the 0 position. In yours "tops"
NSString *topDirPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:0]];
// This will return the file path in your "tops" folder
NSString *filePath = [topDirPath stringByAppendingPathComponent:@"MYIMAGE"];
Run Code Online (Sandbox Code Playgroud)

存储图像文件

NSData *imageDataToStore = UIImagePNGRepresentation(image);
[imageDataToStore writeToFile:filePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)

检索图像文件

// Convert the file into data and then into image.
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath];
UIImage *yourImage =  [UIImage imageWithData:imageData];
Run Code Online (Sandbox Code Playgroud)