问题
@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