iOS의 Runtime - 어떻게 우아하게 category에서 클래스에 속성을 연결합니까

1426 단어
category에서 클래스에 속성을 연결하고 이 속성으로 일을 합니다.이럴 때 우리는 보통 런타임 지식을 사용한다.코드는 다음과 같습니다.
#import 

@interface UIViewController (BackgroundColor)

@property (nonatomic, strong) UIColor *backgroundColor;

@end
#import "UIViewController+BackgroundColor.h"
#import 
#import 

// 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

좋은 웹페이지 즐겨찾기