How to check if a directory exists in Objective-C

n.evermind picture n.evermind · Sep 24, 2011 · Viewed 32k times · Source

I guess this is a beginner's problem, but I was trying to check if a directory exists in my Documents folder on the iPhone. I read the documentation and came up with this code which unfortunately crashed with EXC_BAD_ACCESS in the BOOL fileExists line:

 -(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];

    BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:YES];

    if (fileExists)
    {
        NSLog(@"Folder already exists...");
    }

}

I don't understand what I've done wrong? It looks all perfect to me and it certainly complies with the docs, not? Any revelations as to where I went wrong would be highly appreciated! Thanks.

UPDATED:

Still not working...

  -(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];

    BOOL isDir;
    BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDir];

    if (fileExists)
    {


        if (isDir) {

            NSLog(@"Folder already exists...");

        }

    }

}

Answer

sidyll picture sidyll · Sep 24, 2011

Take a look in the documentation for this method signature:

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

You need a pointer to a BOOL var as argument, not a BOOL itself. NSFileManager will record if the file is a directory or not in that variable. For example:

BOOL isDir;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if (exists) {
    /* file exists */
    if (isDir) {
        /* file is a directory */
    }
 }