如何检查目录是否存在于Objective-C中 [英] How to check if a directory exists in Objective-C

查看:400
本文介绍了如何检查目录是否存在于Objective-C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这是一个初学者的问题,但我试图检查一个目录是否存在于我的文档文件夹中的iPhone。我读了文档,并提出了这个代码,不幸的是在BOOL fileExists行中的EXC_BAD_ACCESS崩溃:

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:

仍然无法运作...

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

        }

    }

}


推荐答案

请参阅文档此方法签名:

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


b $ b

你需要一个指向BOOL var作为参数的指针,而不是BOOL本身。 NSFileManager将记录该文件是否是该变量中的目录。例如:

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

这篇关于如何检查目录是否存在于Objective-C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆