本文介绍了为什么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];
 }

为什么没有像大多数其他物体消息传递模式在上述工作的工作?为什么一定不是我们使用的错误:(NSError **)误差

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需要双间接? (指针的指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:21