NSCopyObject 被认为有害吗?

发布于 2024-09-13 21:51:46 字数 840 浏览 1 评论 0原文

在 Xcode 文档中 NSCopyObject,特殊注意事项部分指出:

这个功能很危险,而且很难正确使用。任何可以子类化的类将其用作 copyWithZone: 的一部分,非常容易出错。在 GC 下或使用 Objective-C 2.0 时,该区域被完全忽略。

此功能可能在 Mac OS X 10.6 后被弃用。

为什么很难正确使用?它执行浅(逐位)复制。对象不会被复制或保留。文档对此非常清楚。

如果我没有遗漏其他原因,执行对象浅复制的首选替代方案是什么?

编辑:

有充分的理由想要执行浅复制。一个例子:一个类可能有许多实例变量,其中大多数是原始类型(整数、浮点数)或故意不保留以避免保留循环的对象(委托)。使用 NSCopyObject 的浅拷贝将所有这些复制到一行漂亮的自记录代码中。任何剩余的需要进行引用计数的 ivars 都可以单独保留或复制。

另一种方法是使用指针语法 (newObject->ivar = ivar) 分配给新对象,或者创建一个具有潜在大量参数的 init 方法(每个 ivar 一个参数)复制)。后者让我觉得特别难看,但我想它不需要出现在标题中并向世界公开。

In the Xcode documentation for NSCopyObject, the special considerations section states:

This function is dangerous and very difficult to use correctly. It's use as part of copyWithZone: by any class that can be subclassed, is highly error prone. Under GC or when using Objective-C 2.0, the zone is completely ignored.

This function is likely to be deprecated after Mac OS X 10.6.

Why is it difficult to use correctly? It performs a shallow (bit-for-bit) copy. Objects are not copied or retained. The documentation is pretty clear on this.

If I'm not missing other reasons, what is the preferred alternative for performing a shallow copy of an object?

Edit:

There are valid reasons to want to perform a shallow copy. One example: a class may have many instance variables, most of which are primitive types (integer, float) or objects that are intentionally not retained to avoid retain cycles (delegates). A shallow copy using NSCopyObject copies all of these in one nice, self-documenting line of code. Any remaining ivars that do need to be reference counted can be retained or copied individually.

The alternative to this is to either assign to the new object using pointer syntax (newObject->ivar = ivar) or to create an init method with a potentially large number of arguments (one for each ivar to copy). The latter strikes me as especially ugly, but I suppose it doesn't need to be in the header and exposed to the world.

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

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

发布评论

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

评论(1

爱你是孤单的心事 2024-09-20 21:51:46

您不应该制作不涉及正确保留/释放的浅复制。时期。

You shouldn't make a shallow copy not involving the correct retain/release. Period.

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