4

我想创建多个目录,我不知道如何。这是我到目前为止的代码。

- (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 bottoms right 和 left 的目录,但是如果我以上述方式执行此操作,它将不起作用。有没有办法使用此代码创建多个目录?还是我的代码错了?谢谢!

4

1 回答 1

9

试试这个代码。

按照您的要求创建目录。

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];
于 2013-08-05T11:13:24.427 回答