我可以使用类别覆盖超类中本身属于类别的方法吗? [英] Can I use a category to override a method which is itself in category on the superclass?

查看:81
本文介绍了我可以使用类别覆盖超类中本身属于类别的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@interface MySuperclass : NSObject {

}

@end

@interface MySuperclass (MyCategory)

- (void)myMethod;

@end

@interface MySubclass : MySuperclass {

}

@end

@interface MySubclass (MyOtherCategory)

- (void)myMethod;

@end

是否定义了-myMethod的哪个实现?

Is it defined which implementation of -myMethod will be called?

科尚在Objective-C编程中指出:

Kochan states in Programming in Objective-C that:


如果更多不是一个类别为同一个类声明了一个具有相同名称的方法,没有定义在调用时将执行哪个方法。

If more than one category declares a method with the same name for the same class, it is not defined which method will be executed when invoked.

但是我不确定在这种情况下是否将超类的类别视为同一类的类别。

But I am not sure whether or not a category on a superclass is considered to be a category on the same class in this context.

推荐答案

虽然找不到参考文献,但我认为很明显, MySubclass(MyOtherCategory)中的实现优先。类别的方法已添加到该特定类中,因此 MyOtherCategory实现将属于您的子类,并且在消息分发期间继续进行父类查找之前将对其进行查找。

Although I can't find a reference, I think it's clear that the implementation in MySubclass (MyOtherCategory) takes precedence. The category's methods are added to that particular class, so the "MyOtherCategory" implementation will belong to your subclass, and it will be looked up before going on to the superclass during message dispatch.

正如Objective-C手册中指出的那样,可可中的许多方法都归类。如果查找顺序定义不正确,则您将无法覆盖子类类别中的所有这些方法,这将使类别几乎无用。

As pointed out in the Objective-C manual, a lot of methods in Cocoa are placed in categories. If the order of look-up wasn't well defined, you couldn't override any of those methods in categories on subclasses, which would make categories almost useless.

这篇关于我可以使用类别覆盖超类中本身属于类别的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆