Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

iphone - How to check if a directory exists in Objective-C

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...");

        }

    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 */
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...