如何在多种方法中冒泡错误对象?
这更像是一个 C 问题,但就这样吧。
我有一个方法,它接收指向 NSError 对象的指针的地址作为参数。现在,该方法被埋藏在类层次结构深处的几层中,我需要使错误对象一直冒泡到顶部。
我可以在每个方法上返回错误对象,但我宁愿以 Cocoa 方式执行,并在将错误对象作为参数传递时返回布尔值。
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cocoa 方式是布尔直接返回,并通过引用(即通过指针)返回错误值,如下所示:(
或者,
trySomething:error:
可能返回一个对象,在这种情况下您将该对象视为布尔返回:非nil
为 true/成功,nil
为 false/失败。)为了使其可链接,每个方法(最外面的方法除外)应该有一个错误指针参数,并在其实现中使用它:
您可以结合这两种方法,在您自己的局部变量中捕获错误对象,以便在将自定义/包装错误存储在失败案例中之前对其进行自定义或包装。供调用者接收的错误返回指针。
The Cocoa way is the Boolean direct return with a by-reference (i.e., through pointer) return of the error value, like so:
(Alternatively,
trySomething:error:
may return an object, in which case you treat that object as the Boolean return: non-nil
is true/succeeded,nil
is false/failed.)To make this chainable, each method (except the outermost) should have an error-pointer parameter, and use that in its implementation:
You can combine both approaches, catching the error object in your own local variable in order to customize or wrap it in the failure case before storing the customized/wrapper error at the error-return pointer for your caller to receive.