About category in Object-C: Override existed message
Category is alternative of subclassing. What will happen if the category message already has been implemented in the class. Take UIViewController as example,
@implementation UIViewController (Landscape)
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
@end
So if we get any XXViewController which extends UIViewController, is that the default message will be implemented like above ?
- (BOOL)shouldAutor开发者_开发知识库otateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
As you can see that I aim to make all XXViewController support landscape, so use category to reach this purpose.
Actually the traditional strategy will use subclass, and it works. How about the category way ?
Thanks
Categories can indeed override methods; your code snippet is perfectly legal and should do what you want.
You do have to be careful, however, as if 2 categories override the same method you will get undefined results. Also, a category might be a bad choice if in the future you want some view controllers to be portrait.
Subclassing is probably the best option here.
You may want to use Class Cluster approach, or methods swizzling.
A topic with similar question has been already covered here: Category conflicts
精彩评论