【问题标题】:NSLog, NSError, bad accessNSLog,NSError,访问错误
【发布时间】:2010-12-25 18:29:41
【问题描述】:

我正在对 NSPersistentStoreCoordinator 执行一个相当普通的 addPersistentStore,它生成了一个 &error 代码。

于是我去了NSLog它,当我这样做时遇到了访问错误:

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

这似乎是常见的成语。

当我重新格式化错误语句如下:

     NSLog(@"Unresolved error   %@",   [error userInfo]);

...问题消失了。

甚至 NSZombie 也没有正确捕获错误的访问错误!

有什么想法吗?

【问题讨论】:

    标签: objective-c cocoa nslog nserror


    【解决方案1】:

    不要忘记用 nil 值初始化 NSError

    NSError* err = nil;
    [anObject doSomethingGetError:&err];
    if (err) {
        NSLog(...);
    }
    

    如果这没有帮助,那就是 API 错误

    【讨论】:

    • 如果 API 用无效(或有效但无意义的)对象破坏了您的 nil 初始化程序,那将无济于事。请参阅我的回答和它引用的来自@bbum 的推文。
    • 如果没有任何错误,API 不会触及“err”引用 [即 nil]。 - (NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(NSString *)configuration URL:(NSURL *)storeURL options:(NSDictionary *)options error:(NSError **)error;此方法返回不是 BOOL 类型
    • 实际上,将 err 对象设置为 nil 仅表示您有兴趣检查 err 对象是否应该发生。 @Peter Hosey 的回答显示了确定方法调用是否成功的正确方法。
    • @vaddieg 您通常可以从返回值中判断调用是否成功,文档对此总是很清楚。例如。在这种情况下:“新创建的商店,或者,如果发生错误,则为零。”。
    • vaddieg:不,这不正确。再次,请参阅我在回答中引用的来自@bbum 的推文。一些 API确实写入错误变量(从而破坏了您初始化它的 nil),即使 API 在返回时成功。
    【解决方案2】:

    你是如何发现错误的?

    正确的做法,如described by bbum,是:

    NSError *error;
    BOOL success = [blah blah:blah error:&error];
    if (!success) {
        NSLog(@"Error: %@ %@", error, [error userInfo]); //Or other error handling (e.g., [NSApp presentError:error]).
    } else {
        //Succeeded—ignore the error variable entirely
    }
    

    (这是用于返回 BOOL 的方法 blah:error:;bbum 回答的问题中的示例是用于返回对象的方法。两种情况的错误处理模式相同。)

    根据他不久之后的 Twitter 更新,some APIs will output an error object under the hood even if what you asked for succeeded,这意味着测试错误变量而不是 BOOL 返回可以欺骗你。我想这就是发生在你身上的事情。

    解决方案是在 API 报告失败时查看错误对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2017-01-19
      • 2018-10-05
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多