The documentation is not quite clear on the matter. Apart from what has been mentioned so far, at some other point in the docs, it says: "When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that already existed in the category's class, there is no way to invoke the original implementation" - which I read as "the category implementation will always run instead of the original implementation".
I've read this before but didn't find it just now, however it has been mentioned in this SO answer.
Personally, I've been frequently overwriting methods using categories and so far, it has caused me no trouble. However since I know I'd "kill" the original implementation, I'm careful about doing it only with methods for which it is safe to assume that the class is inheriting the original implementation from a superclass.
For example, I'd consider it safe to override touchesBegan:withEvent:
in a category on UIView
, since that method has been inherited from UIResponder
and the original implementation remains untouched and can (and should) be reached by calling super
from within the implementation of the category.
To my knowledge, abstract or empty implementations are safe to override, too. For example, I've been overriding awakeFromNib
in UIScrollView
to overcome the problem with the scrollview not setting its contentSize property according to the actual content size on its own, in case it has been created in Interface Builder:
@implementation UIScrollView (MyHandyCategory)
-(void)awakeFromNib {
[self autoResizeContent];
}
-(void)autoResizeContent {
NSArray *subViews = [self subviews];
UIView *contentView = [subViews objectAtIndex:0];
[self setContentSize:contentView.frame.size];
}
@end
In case you wonder why I didn't just put the autoresize code in awakeFromNib - I wanted to be able to call autoresize on other occasions as well. In my actual category, there is more code in awakeFromNib which I don't necessarily want to run along with the autoresize code.