O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.3. Creating Folders on Disk

Problem

You want to be able to create folders on disk to save some of your app’s files in them.

Solution

Use the createDirectoryAtPath:withIntermediateDirectories:attributes:error: instance method of the NSFileManager class, as shown here:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    
    NSString *tempDir = NSTemporaryDirectory();
    NSString *imagesDir = [tempDir stringByAppendingPathComponent:@"images"];
    
    NSError *error = nil;
    if ([fileManager createDirectoryAtPath:imagesDir
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error]){
        
        NSLog(@"Successfully created the directory.");
        
    } else {
        NSLog(@"Failed to create the directory. Error = %@", error);
    }
    
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Discussion

The APIs exposed by NSFileManager are very easy to use, and it’s no surprise that you can use them to create folders on disk in a few lines. The createDirectoryAtPath:withIntermediateDirectories:attributes:error: method may look scary at first, but it’s not that bad. I will explain the different parameters that you can pass to it:

createDirectoryAtPath

The path to the folder that has to be created.

withIntermediateDirectories

A Boolean parameter that, if set to YES, will create all the folders in the middle ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required