【问题标题】:Proper way of handling reference to NSError处理对 NSError 的引用的正确方法
【发布时间】:2013-05-14 13:10:28
【问题描述】:

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

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]);
}

我还附上了控制台的输出:

【问题讨论】:

  • @Wain 虽然这可能适用于大多数实际目的,但不能保证它有效,因为在方法执行期间指针可能会更改为无效值。 error 的值只有在方法返回 NO 时才有效。
  • @gaige 没错,它不应该发生,但它确实会发生。
  • @Wain 不,没有理由将error 指针初始化为nil,并且使用if (error) ... 永远无效。

标签: objective-c nserror


【解决方案1】:

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

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

例如:

if (![fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:&error]) {
    NSLog(@"%@", [error localizedDescription]);
}

【讨论】:

  • 那么这是一个更好的方法吗? if (![fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES 属性:nil error:&error]) NSLog(@"%@", [error localDescription]);
  • 是的,我只是将其添加到我的答案中;-)
  • 在这种情况下还要检查是否创建了 NSArray? NSError *error = nil; NSArray *downloads = [self.managedObjectContext executeFetchRequest:allDownloads error:&error];
  • executeFetchRequest:error:的情况下,您需要检查downloads是否为nil。如果是nil,则error有效,否则为undefined。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 2011-02-28
  • 2016-01-15
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 2015-04-20
相关资源
最近更新 更多