为什么 NSError 需要双重间接?(指向一个指针的指针) [英] Why does NSError need double indirection? (pointer to a pointer)

查看:23
本文介绍了为什么 NSError 需要双重间接?(指向一个指针的指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个概念似乎困扰着我.为什么 NSError 对象需要将其指针传递给正在修改该对象的方法?例如,不只是传递对错误的引用会做同样的事情吗?

This concept seems to trouble me. Why does an NSError object need its pointer passed to a method that is modifying the object? For instance, wouldn't just passing a reference to the error do the same thing?

NSError *anError;
[myObjc doStuff:withAnotherObj error:error];

然后在 doStuff 中:

and then in doStuff:

 - (void)doStuff:(id)withAnotherObjc error:(NSError *)error 
 {
    // something went bad!
    [error doSomethingToTheObject];
 }

为什么上述工作不像大多数其他对象消息传递模式那样工作?为什么我们必须使用 error:(NSError **)error?

Why doesn't the above work like most other object messaging patterns work? Why must instead we use error:(NSError **)error?

推荐答案

NSError** 模式用于当方法通常返回某个值但可能需要返回错误对象(类型为NSError*) 如果失败.在 Objective-C 中,一个方法只能返回一种类型的对象,但在这种情况下,您想要返回两种类型.在类 C 语言中,当你需要返回一个额外的值时,你需要一个指向该类型值的指针,所以要返回一个 NSError* 你需要一个 NSError** 参数.一个更现实的例子是:

The NSError** pattern is used when a method normally returns some value but instead may need to return an error object (of type NSError*) if it fails. In Objective-C a method can only return one type of object, but this is a case where you want to return two. In C-like languages when you need to return an extra value you ask for a pointer to a value of that type, so to return an NSError* you need an NSError** parameter. A more realistic example would be this:

// The method should return something, because otherwise it could just return
// NSError* directly and the error argument wouldn't be necessary
- (NSArray *)doStuffWithObject:(id)obj error:(NSError **)error
{
  NSArray *result = ...;  // Do some work that might fail
  if (result != nil) {
    return result;
  } else {
    // Something went bad!
    // The caller might pass NULL for `error` if they don't care about
    // the result, so check for NULL before dereferencing it
    if (error != NULL) {
      *error = [NSError errorWithDomain:...];
    }
    return nil;  // The caller knows to check error if I return nil
  }
}

如果您只有一个 NSError* 参数而不是 NSError** 那么 doStuff 将永远无法将错误对象传回给它的调用者.

If you only had an NSError* parameter instead of an NSError** then doStuff would never be able to pass the error object back to its caller.

这篇关于为什么 NSError 需要双重间接?(指向一个指针的指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆