iOS之Runtime——如何优雅地在category中给类关联
2016-04-01 本文已影响430人
jueyingxx
在category中给类关联一个属性,并用这个属性去做一些事。
这个时候,通常我们会用到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