【问题标题】:How to correctly handly NSError** pointers?如何正确处理 NSError** 指针?
【发布时间】:2018-10-30 10:41:08
【问题描述】:

处理 NSError** 指针的正确方法是什么?

- (BOOL)handleData:(NSDictionary *)data error:(NSError **)error {
    // pass the error pointer to NSJSONSerialization
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:options error:error];

    // Check if NSJSONSerialization had errors
    if (error)  // <-- sometimes this works, sometimes it crashes...
       return false;

    ...

    return true;
}

- (void)someMethod {
    NSError *error = nil;
    BOOL result = [self handleData:dataDict error:&error]; 

    if (error) {
       // an error occurred
    } else {

    }
}

在此示例中,someMethodNSError 引用传递给 handleData:error。这是通过传递指针/地址而不是对象来完成的 (...error:&amp;error)

方法handleData:error 然后将此指针传递给dataWithJSONObject:options:error(现在没有&amp;)。现在我想检查是否发生了错误,但正确的方法是什么?

if (error)...   
// This works if error == nil. However this is not always the case. 
// Sometimes error is some address (e.g. 0x600001711f70) and *error == nil
// from the start of the method (passing error to NSJSONSerialization has no 
// influence on this

if (*error)...
// This works in cases where error itself is not nil, but it crashes if
// error == nil

为什么在某些情况下是 error == nil 而在其他情况下是 error != nil 而在其他情况下是 *error == nil

在方法之间传递错误并检查是否发生错误的正确方法是什么?

【问题讨论】:

  • Sometimes error is some address (e.g. 0x600001711f70) - 嗯,呃。您将指向 NSError* 的指针传递给该方法,并将错误信息写入该方法。
  • 不,正如 error != nil 所解释的那样,有时在输入 handleData:error 之后会出现这种情况,然后将错误传递给 dataWithJSONObject:options:error。即使error != nil 为真,*error 仍然为零...

标签: objective-c pointers nserror


【解决方案1】:

找到答案的地方是Introduction to Error Handling Programming Guide For Cocoa。约定是:

  1. 一个方法可以通过NSError **参数返回一个NSError对象,这样的方法也应该有一个非void的返回类型,并通过它的返回值指示成功或失败。因此,使用您的示例,dataWithJSONObject:options:error: 在遇到错误时将返回 nil,并且可能通过其第三个参数返回错误对象。

  2. 任何接受NSError ** 参数以返回错误的方法都应接受NSError * 变量的地址 NULL。后一个值意味着用户不希望返回错误对象。这意味着接受NSError ** 参数的方法必须在尝试通过它分配错误对象之前检查参数值不是NULL

所以你的方法handleData:error: 必须准备好接受NULL 并且需要对其进行测试。因此,您的代码必须包含类似以下内容:

// Check if NSJSONSerialization had errors
if (jsonData == nil)
{
   // Error occurred, did it return an error object?
   if (error != NULL && *error != nil)
   {
       // we have an error object
   }
   else
   {
      // we have an error but no error object describing it
   }
}
else
{
   // no JSON error
}

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2015-12-31
    • 2017-01-26
    • 2019-10-18
    • 1970-01-01
    • 2016-12-26
    • 2019-01-08
    相关资源
    最近更新 更多