Objective-c 中返回错误
我对 Objective-C 很陌生,我开始想知道处理和捕获错误的常见/标准/正确方法是什么?
似乎可以使用 NSError 来做到这一点,这是一个好主意还是对可可的劫持?
Im newish to objective-c and am starting to wonder what is the common/standard/proper way for handling and catching errors?
It seems like it might be possible to use NSError to do this, is that a good idea or a hijack of cocoa?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很确定这就是 NSError 类的作用 - 提供有关错误的详细信息。您将看到的最常见的模式是采用指向 NSError 对象的指针的方法,如下所示:
该方法为执行某些操作的结果返回一些值(或可能为 nil),但是如果调用失败将在传递的指针处放置一个 NSError 对象,其中包含有关失败的详细信息。您的文档负责指定方法遇到错误时返回的内容。
我想到的另一个方法是@throw-@catch块;然而,在 Objective-C 中 @throw 异常的计算量可能相当大,并且通常只建议在真正的异常情况下这样做。
编辑:哇,事实证明很多人对
@throw
异常有非常强烈的看法。总结一下关于这个问题的(非常有帮助的)评论:error
方法或发布 NSNotification 实例。@throw
/@catch
块,请非常小心它们周围的逻辑。 Objective-C 提供了很多方法来分离方法以在其他线程中运行,或延迟执行等。在编写代码时要非常小心地考虑所有这些可能性。最后,另一个非常有效的观点:
error
对象,则返回值应该指出它。不要尝试同时执行这两项操作(返回部分有效的对象并设置错误
对象)。I'm pretty sure that's what the NSError class is there to do - give details about errors. The most common pattern you'll see is a method that takes a pointer to an NSError object, as in:
The method returns some value (or possibly
nil
) for the result of doing something, but if the call failed will place an NSError object at the pointer passed with details about the failure. Your documentation is responsible for specifying what gets returned if the method does encounter an error.The other method that comes to mind is the
@throw
-@catch
block; however, in Objective-C@throw
ing an exception can be rather computationally expensive, and it's usually only recommended to do so in truly exceptional situations.Edit: wow, turns out a lot of people have really strong opinions about
@throw
ing exceptions. To sum up the (quite helpful) commentary on the issue:error
method demonstrated above or post instances of NSNotification.@throw
/@catch
blocks, be very careful about the logic surrounding them. Objective-C provides a lot of ways to detach methods to run in other threads, or delay execution, etc. Be very careful to account for all those possibilities when you write your code.Finally, another very valid point:
error
object passed to a method, the return value should indicate it. Don't try to do both (return a partially valid object and set theerror
object).