I have seen a class which implements a catagory on itself. The code is as follow:
.h file:
#import <UIKit/UIKit.h>
@interface BPTopTabBarViewController : UIViewController
@end
@interface UIViewController (BPTopTabBarViewController)
@property (nonatomic, readonly) BPTopTabBarViewController *topTabBarViewController;
@end
.m file:
#import "BPTopTabBarViewController.h"
#import <objc/runtime.h>
@implementation UIViewController (BPTopTabBarViewController)
- (BPTopTabBarViewController *)topTabBarViewController
{
return objc_getAssociatedObject(self, BPTopTabBarViewControllerKey);
}
- (void)setTopTabBarViewController:(BPTopTabBarViewController *)topTabBarViewController
{
objc_setAssociatedObject(self, BPTopTabBarViewControllerKey, topTabBarViewController, OBJC_ASSOCIATION_ASSIGN);
}
@end
@interface BPTopTabBarViewController () {
}
@end
@implementation BPTopTabBarViewController
...
@end
My Questions are:
What is the point of introducing a getter and setter on itself with a category of UIViewController? According to me only the class of BPTopTabBarViewController or the subclass of it can see the category because there is no category header(#import "UIViewController + BPTopTabBarViewController") declared in .h file.
I can see UINavigationController also have some structure like this:
@interface UIViewController (UINavigationControllerItem)
Here we can always call a class of UIViewController or its subclass self.navigationController, how is the category exposed to UIViewController when it is written in UINavigationController class? I also don't see the category header in UINavigationController.h file:
// Copyright (c) 2007-2014 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIViewController.h>
#import <UIKit/UIKitDefines.h>
#import <UIKit/UIInterface.h>
#import <UIKit/UIGeometry.h>
#import <UIKit/UIPanGestureRecognizer.h>
#import <UIKit/UITapGestureRecognizer.h>
If I want to expose the category to specific UIViewController class, what should I do?
If I want to expose the category globally, should I put #import "BPTopTabBarViewController.h" into project-Prefix.pch file?