美文网首页
iOS之Runtime——如何优雅地在category中给类关联

iOS之Runtime——如何优雅地在category中给类关联

作者: jueyingxx | 来源:发表于2016-04-01 13:56 被阅读430次

在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

相关文章

网友评论

      本文标题:iOS之Runtime——如何优雅地在category中给类关联

      本文链接:https://www.haomeiwen.com/subject/wprylttx.html