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

时间:2013-08-05 11:01:46

标签: iphone ios directory 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

}

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

1 个答案:

答案 0 :(得分: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
}

在您的应用中的任何位置使用您创建的目录。

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"];

存储图像文件

NSData *imageDataToStore = UIImagePNGRepresentation(image);
[imageDataToStore writeToFile:filePath atomically:YES];

检索图像文件

// Convert the file into data and then into image.
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath];
UIImage *yourImage =  [UIImage imageWithData:imageData];