I have category for supporting portrait only when vc is presented over another vc. To use that, normally we use import UINavigationController+Portrait.h. However, when I try to call in another vc, although I haven't import yet, supportedInterfaceOrientations is always calling in my category. May I know what is wrong?
#import "UINavigationController+Portrait.h"
@implementation UINavigationController (Portrait)
- (BOOL)shouldAutorotate
{
return NO;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
//ios4 and ios5
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return NO;
}
When you create a category in Objective-C, any methods you define will affect every instance of the class the category is created for – it doesn't only take effect in files where you import the category.
The Objective-C runtime is dynamic, meaning that when you call a method, it will look up the method on the appropriate class and call it. When you override that method via a category, even without importing it anywhere, the runtime will look for the right method to call and find that the one defined in the category is available and instead call that.
That's the reason that all instances of UIViewController
now find your category's method instead.
Because of this, overriding methods in categories is pretty dangerous. Instead, the right thing to do is to subclass a class and override its methods there. If that isn't an option, method swizzling is another way of doing it, but that also has its own risks.