iosobjective-cfilesystemsnsfilemanagernsdocumentdirectory

Is there a safer way to create a directory if it does not exist?


I've found this way of creating a directory if it does not exist. But it looks a bit wonky and I am afraid that this can go wrong in 1 of 1000 attempts.

if(![[NSFileManager defaultManager] fileExistsAtPath:bundlePath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:NULL];
}

There is only this awkward method fileExistsAtPath which also looks for files and not only directories. But for me, the dangerous thing is: What if this goes wrong? What shall I do? What is best practice to guarantee that the directory is created, and only created when it does not exist?

I know file system operations are never safe. Device could loose battery power suddenly just in the moment where it began shoveling the bits from A to B. Or it can stumble upon a bad bit and hang for a second. Maybe in some seldom cases it returns YES even if there is no directory. Simply put: I don't trust file system operations.

How can I make this absolutely safe?


Solution

  • You can actually skip the if, even though Apple's docs say that the directory must not exist, that is only true if you are passing withIntermediateDirectories:NO

    That puts it down to one call. The next step is to capture any errors:

    NSError * error = nil;
    [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath
                              withIntermediateDirectories:YES
                                               attributes:nil
                                                    error:&error];
    if (error != nil) {
        NSLog(@"error creating directory: %@", error);
        //..
    }
    

    This will not result in an error if the directory already exists.