2

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)shouldAutorotateToInterfaceOrientation:(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

Forrest
  • 122,703
  • 20
  • 73
  • 107

2 Answers2

3

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.

cobbal
  • 69,903
  • 20
  • 143
  • 156
1

You may want to use Class Cluster approach, or methods swizzling.

A topic with similar question has been already covered here: Category conflicts

Community
  • 1
  • 1
Martin Babacaev
  • 6,240
  • 2
  • 19
  • 34