1

This is more of a C question but here it goes.

I've a method that receives as a parameter the address of a pointer to an NSError object. Now, that method is buried several levels deep in the class hierarchy and I need to make the error object bubble all the way to the top.

I could return the error object on each method but I'd rather do it the Cocoa way and return a boolean while passing the error object as a parameter.

How can I do this?

4

1 回答 1

1

我可以在每个方法上返回错误对象,但我宁愿使用 Cocoa 方式并在将错误对象作为参数传递时返回一个布尔值。

Cocoa 方式是通过引用(即通过指针)返回错误值的布尔直接返回,如下所示:

NSError *error = nil;
if ([foo trySomething:bar error:&error]) {
    //Success!
} else {
    //Failure!
}

(或者,trySomething:error:可能返回一个对象,在这种情况下,您将该对象视为布尔返回:非nil为真/成功,nil为假/失败。)

为了使这个可链接,每个方法(除了最外面的)都应该有一个错误指针参数,并在其实现中使用它:

- (void) trySomething:(MyBar *)bar error:(out NSError **)outError
    if ([bartender restock:bar error:outError]) {
        //Success!
    } else {
        //Failure!
    }
}

您可以结合这两种方法,在您自己的局部变量中捕获错误对象,以便在将自定义/包装错误存储在错误返回指针中以供调用者接收之前对其进行自定义或包装在失败案例中。

于 2010-12-18T22:12:50.743 回答