1

我的代码看起来像这样,有时应用程序在尝试记录错误时会在最后一行崩溃。我究竟做错了什么?

BOOL isDir;
NSError *error;
NSString *downloadPath = [[NSString stringWithFormat:@"%@/%@", [download downloadFolder], [download escapedTitle]] stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:downloadPath isDirectory:&isDir])
{
    [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:&error];

    if (error)
        NSLog(@"%@", [error localizedDescription]);
}

我还附上了控制台的输出: 在此处输入图像描述

4

1 回答 1

4

在 Cocoa 中,NSError **只有当被调用的方法返回错误时才有效,在这种情况下,如果-createDirectoryAtPath:...返回 false。

不要测试if (error),而是测试方法的返回值是否-createDirectoryAtPath:为假,这样就可以了。

例如:

if (![fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:&error]) {
    NSLog(@"%@", [error localizedDescription]);
}
于 2013-05-14T13:16:54.907 回答