objective-c - 检查目录是否存在时如何避免 EXC_BAD_ACCESS?

标签 objective-c ios cocoa-touch exc-bad-access nsfilemanager

我正在构建一个将图像缓存在应用程序包的文档目录中的应用程序。为了确保目录存在,我想检查它们是否存在,如果不存在,则在应用程序启动时创建它们。

目前,我在 didFinishLaunchingWithOptions: 中这样做:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSArray *directoriesToCreate = [[NSArray alloc] initWithObjects:
                                    @"DirA/DirA1",
                                    @"DirA/DirA2",
                                    @"DirB/DirB2",
                                    @"DirB/DirB2",
                                    @"DirC",
                                    nil];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    for (NSString *directoryToCreate in directoriesToCreate) {

        NSString *directoryPath = [documentsPath stringByAppendingPathComponent:directoryToCreate];
        NSLog(directoryPath);
        if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES]) {

            NSError *directoryCreateError = nil;
            [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:&directoryCreateError];


        }

    }

    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;

}

在应用程序第一次运行时——当不存在任何目录时——应用程序运行,目录按预期创建,一切运行正常。

当应用程序终止并再次运行时,我在 [NSFileManager defaultManager] 上的 fileExistsAtPath: 调用上收到 EXC_BAD_ACCESS 信号。

我不明白的是为什么当目录不存在时它运行得很好,但当它们存在时它就会失败。

谁能提供任何帮助?

最佳答案

您以错误的方式使用了检查功能。第二个参数必须是指向 bool 变量的指针,该变量将在调用函数后填充:

你正在使用这样的函数:

[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES];

但是函数应该这样使用:

BOOL isDir;
[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir];

if (isDir) { // file exists and it is directory.

关于objective-c - 检查目录是否存在时如何避免 EXC_BAD_ACCESS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6679489/

相关文章:

objective-c - 如何关闭 iOS 5 中的弹出窗口?

objective-c - 如何在 objective-c 中比较两个具有很多属性的对象

ios - tableviewcell中的Segment控件

cocoa-touch - 自动订阅应用内购买 : Restoring Subsequent Renewals

ios - 测量蜂窝信号强度

ios - 截断 NSAttributedString 中的部分字符串

ios - cocoa touch 中多个 NSNotifcationCenter 实例的缺点

iphone - 我想在检测到触摸点时移动 Sprite 体

ios - 如何从嵌入到 iPhone 肖像图片中的深度数据计算距离值?

iphone - 使用 UIBackgroundModes 在后台模式下运行代码