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

在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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,992评论 0 9
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,842评论 33 466
  • 对于从事 iOS 开发人员来说,所有的人都会答出【runtime 是运行时】什么情况下用runtime?大部分人能...
    梦夜繁星阅读 3,796评论 7 64
  • 据说这部影片是通过一个真实的故事改编制作完成的。故事讲的是一个发生在英国历史上的一个真实事件,述说的是英国的一艘名...
    无边风雨阅读 584评论 1 1
  • 谁都说不清明天会发生什么,所以做了就是做了,别后悔,做一件少一件,别给自己留有遗憾。 听到老年人自己说自己活不过今...
    净土1990阅读 957评论 0 0

友情链接更多精彩内容