wujek
wujek

Reputation: 11040

Categories overriding methods in UIViewControllers not working - method never called

I have an iPad 3 app that I want to only be viewable in landescape mode. I have a few UIViewContoller subclasses (it is a really simple app), and in all of them I have the following code:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

The code is not big, but duplicated, and I would like to learn ways one can avoid this in Objective-C. I read about categories, and how they can override methods from classes / instances they apply to, so decided to try. I used the Xcode wizard to create a LandscapeOnly category for a UIViewController class, and moved the above implementation to it - to no avail. I tried adding the method signature to the header file, but this also didn't change anything.

How is this done? How can I use categories to override instance methods?

I read in another question here that categories and overriding methods is discouraged, so maybe I am wrong all along? What is the canonical way of achieving what I would like to achieve? I can use a custom UIViewController subclass, and have all other controllers derive from it, but this will break as soon as I have controllers with differing requirements, and hence multiple base classes. In other languages I would use mixins, for example, and I think Objective-c categories are their counterpart?

Upvotes: 0

Views: 824

Answers (1)

Alex Chan
Alex Chan

Reputation: 161

Categories are used to add additional methods to the class but not for overriding.

I think you can create a UIViewController subclass that overrides the method you mentioned and use this subclass as the super class of all your view controller so as to eliminate duplicate codes.

Secondly, you can use class_replaceMethod or method_exchangeImplementations to replace / exchange the implementation of the method you mentioned. But it would be dangerous.

Upvotes: 2

Related Questions