代码之家  ›  专栏  ›  技术社区  ›  Andrei Herford

如何正确处理N错误**指针?

  •  0
  • Andrei Herford  · 技术社区  · 7 年前

    - (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 {
    
        }
    }
    

    在这个例子中 someMethod 通过a NSError 参考 handleData:error . 这是通过传递指针/地址而不是对象来完成的( ...error:&error )

    方法 已处理ata:error 然后将此指针传递给 dataWithJSONObject:options:error (现在没有 & ). 现在我想检查发生的错误,但是正确的方法是什么?

    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 其他人呢?

    1 回复  |  直到 7 年前
        1
  •  3
  •   CRD    7 年前

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

    1. 方法可以返回 NSError 通过 NSError ** void 返回类型,并通过其返回值指示成功或失败。以你为例, dataWithJSONObject:options:error: 会回来的 nil 可以 通过第三个参数返回错误对象。

    2. 任何接受 N错误** NSError * NULL 参数 必须 检查参数值是否正确 无效的

    所以你的方法 handleData:error: 必须准备接受 无效的 需要测试一下。因此,您的代码必须包含类似以下内容:

    // 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公司