使用类别在 Objective C 类中添加冲突方法

发布于 2024-11-14 10:55:02 字数 397 浏览 2 评论 0原文

我已将方法 foo 添加到类别 Category1 中的类 MYCustomClass 中,与该类的原始定义分开。然后我在另一个类别 Category2 中添加了另一个方法,也称为 foo。然后,我在 MYCustomClass 的实例上调用 foo。就我而言,正在调用 Category2 中的 foo 。我的问题是:对此有什么解释吗?或者,它是那些“未定义”/“依赖于编译器”的行为之一。另外,是否可以通过指定我想在调用中使用的类别来限定方法调用来处理这种情况。

编辑:我知道我所做的事情不受支持。我只是感兴趣是否有黑客攻击。

I have added a method foo to a class MYCustomClass in a category Category1 separate from the original definition of the class. Then I added another method also called foo in another category Category2. I then call foo on an instance of MYCustomClass. In my case the foo in Category2 is being called. My question is: Is there any explanation for this? Or, is it one of those "undefined"/"compiler dependent" behaviours. Also, is it possible to handle such situations by qualifying the method call by specifying the category I want to be used in the call.

EDIT: I am aware that what I am doing is not supported. I am just interested in if there is a hack around it.

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

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

发布评论

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

评论(2

简美 2024-11-21 10:55:02

当一个类别被加载时,它的方法被插入到现有的方法表中,一旦完成就无法区分它们来自哪里。最后加载的类别获胜。回到 NeXTSTEP 时代,我们有时会故意这样做,作为一种非常笨拙的方法来修复代码中我们没有源代码的损坏方法。

When a category is loaded, its methods are inserted into the existing method table, and there's no way to distinguish where they came from once that's done. The last category to load wins. Back in the NeXTSTEP days, we would sometimes do this deliberately as a very kludgey way to fix a broken method in code for which we didn't have the source.

虚拟世界 2024-11-21 10:55:02

这是未定义的行为。来自 Objective-C 编程语言 文件:

类别无法可靠地覆盖在同一类的另一个类别中声明的方法。

这个问题特别重要,因为许多 Cocoa 类都是使用类别来实现的。您尝试覆盖的框架定义的方法本身可能已在类别中实现,因此未定义哪个实现优先。

不,您不能指定您想要来自 Category1foo 或来自 Category2foo。如果您需要这个,您应该为这些方法指定不同的名称,例如 foo1foo2

It’s undefined behaviour. From the Objective-C Programming Language document:

A category cannot reliably override methods declared in another category of the same class.

This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

And no, you cannot specify that you want foo from Category1, or foo from Category2. If you need this, you should give different names to those methods, e.g. foo1 and foo2.

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