iOS Category添加属性

2021-01-30  本文已影响0人  静守幸福

原则上讲它只能添加方法, 不能添加属性(成员变量),实际上可以通过其它方式添加属性(Runtime)。

举个例子,给系统UIButton添加个model 属性 新建个分类文件
.h文件


@interface UIButton (Property)

@property(nonatomic, strong) id model;

@end

.m文件 需要导入runtime头文件

#import "UIButton+Property.h"
#import <objc/runtime.h>

@implementation UIButton (Property)

- (void)setModel:(id)model{
    objc_setAssociatedObject(self, @selector(model), model, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)model{
    return objc_getAssociatedObject(self, _cmd);
}

@end

上一篇 下一篇

猜你喜欢

热点阅读