在category中給類關(guān)聯(lián)一個屬性备蚓,并用這個屬性去做一些事濒憋。
這個時候壶熏,通常我們會用到runtime的知識贬循。
代碼如下:
#import <UIKit/UIKit.h>
@interface UIViewController (BackgroundColor)
@property (nonatomic, strong) UIColor *backgroundColor;
@end
#import "UIViewController+BackgroundColor.h"
#import <objc/runtime.h>
#import <objc/message.h>
// clear warning
@interface NSObject ()
- (void)_setBackgroundColor:(UIColor *)color;
@end
@implementation UIViewController (BackgroundColor)
- (void)setBackgroundColor:(UIColor *)backgroundColor {
objc_setAssociatedObject(self, @selector(backgroundColor), backgroundColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
void (*msgSend)(id, SEL, id) = (__typeof__(msgSend))objc_msgSend;
msgSend(self, @selector(_setBackgroundColor:), backgroundColor);
}
- (UIColor *)backgroundColor {
return objc_getAssociatedObject(self, @selector(backgroundColor));
}
static inline void __jy_set_viewController_backgroundColor(id self, SEL _cmd, UIColor *color) {
UIViewController *viewController = self;
viewController.view.backgroundColor = color;
}
__attribute__((constructor)) static void __jy_set_viewController_backgroundColor_entry() {
Class cls = NSClassFromString(@"UIViewController");
IMP imp = (IMP)__jy_set_viewController_backgroundColor;
class_addMethod(cls, @selector(_setBackgroundColor:), imp, "v@:@");
}
@end