使用类别在 Objective C 类中添加冲突方法
我已将方法 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当一个类别被加载时,它的方法被插入到现有的方法表中,一旦完成就无法区分它们来自哪里。最后加载的类别获胜。回到 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.
这是未定义的行为。来自 Objective-C 编程语言 文件:
不,您不能指定您想要来自
Category1
的foo
或来自Category2
的foo
。如果您需要这个,您应该为这些方法指定不同的名称,例如foo1
和foo2
。It’s undefined behaviour. From the Objective-C Programming Language document:
And no, you cannot specify that you want
foo
fromCategory1
, orfoo
fromCategory2
. If you need this, you should give different names to those methods, e.g.foo1
andfoo2
.