Can I use a category to override a method which is itself in category on the superclass?

£可爱£侵袭症+ 提交于 2019-12-24 14:28:36

问题


@interface MySuperclass : NSObject {

}

@end

@interface MySuperclass (MyCategory)

- (void)myMethod;

@end

@interface MySubclass : MySuperclass {

}

@end

@interface MySubclass (MyOtherCategory)

- (void)myMethod;

@end

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

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.


回答1:


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.

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.




回答2:


My gut says you'll be fine, but the only way to know is to try. I believe the uncertainty is only within the same class, not the super/subclass relationship.



来源:https://stackoverflow.com/questions/3357282/can-i-use-a-category-to-override-a-method-which-is-itself-in-category-on-the-sup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!