Objective-C 属性设置器如何发出失败信号?

发布于 2024-10-28 00:02:15 字数 164 浏览 6 评论 0原文

假设您有一个具有复制语义的属性。如果复制方法失败,您应该在 setter 中做什么? (我认为这是可能的,因为副本通常以 alloc/init 组合开始,这可能会失败并返回 nil。)Apple 建议返回错误代码而不是使用异常,但 setter 通常具有 void 返回类型。推荐的方法是什么?如何表明发生了错误?

Suppose you have a property with copy semantics. What should you do in the setter if the copy method fails? (I presume this is a possibility, since a copy usually starts with an alloc/init combo, which can fail and return nil.) Apple recommends returning error codes rather than using exceptions, but a setter generally has a void return type. What is the recommended approach? How do you signal that an error has occurred?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里的微风 2024-11-04 00:02:15

苹果公司的建议实际上是,应该为特殊情况保留例外。无论如何,有时这是推荐的编程实践,但在 Objective-C 的情况下,由于异常处理的成本较高,因此得到了加强。

因此,如果您愿意并且适当的话,您可以抛出异常,例如内存不足(复制失败)是(希望如此!)异常。

也就是说,一些编程实践还建议属性不应抛出异常;通常是因为,如果抛出异常,看起来像赋值 obj.property = value; 的东西会令人困惑(与 [obj setProperty:value] 不同)。

这样我们就可以将类型的属性设置为“零”(nil00.0NO等)。

返回错误的更多详细信息记录错误的详细信息,在检测到“零”后可以查询。这本质上是底层(“Unix”)系统调用和许多库函数使用的方法,在返回“零”之前设置 errno 。

The Apple recommendation is really that exceptions should be reserved for exceptional situations. This is sometimes a recommended programming practice anyway, but in the case of Objective-C is reinforced due to the higher cost of exception handling.

So you can throw an exception if you wish and it is appropriate, e.g. running out of memory (copy failed) is (hopefully!) exceptional.

That said, some programming practices also recommend that properties should not throw exceptions; usually on the basis that something that looks like assignment obj.property = value; would be confusing if exceptions were thrown (unlike [obj setProperty:value]).

So that get us to setting the property to the "zero" for the type (nil, 0, 0.0, NO etc.).

To return more details of the error record details of the error which can be queried after the "zero" has been detected. This is essentially the approach used by the underlying ("Unix") syscalls, and many library functions, were errno is set before a "zero" is returned.

秉烛思 2024-11-04 00:02:15

除了您调用的 setter 的属性为 nil 之外,没有其他方法可以发出错误信号。您可以在执行 setter 后检查 nil ,就像在分配/初始化新实例后确认成功一样。

There is no way to signal an error, other than that the property whose setter you called would be nil. You can check for nil after executing the setter, just as you would to confirm success after alloc/init'ing a new instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文