Search code examples
objective-cuinavigationcontrolleruinavigationbarobjective-c-category

Category declaration in *.m file affects whole app


I implemented the following category for UINavigationController inside of one *.m file:

@interface UINavigationController (ConfirmPop) <UINavigationBarDelegate>

@end

@implementation UINavigationController (ConfirmPop)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    ...

    return YES;
}

@end

I was trying to check some conditions before popping the current view controller, and it worked all right but I short noticed that that category affected all UINavigationControllers in my app. Why does that happen? I thought this would only happen if I declared it on a header file and if I imported somewhere - which is not the case.


Solution

  • Categories apply globally. There isn't a way to apply them selectively.

    Categories are used to add new functionality to all instances of that class, especially when your code isn't responsible for creating instances of that class -- otherwise subclassing might be a better choice.

    You could create your own instance of a UINavigationController with the desired behavior and only use it where you want that behavior. Or if that's somehow not possible, you could add property-like methods to the category that toggle the desired behavior on and off.