1、category需要添加属性,可以使用关联对象来扩展对象
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key, id _Nullable value, objc_AssociationPolicy policy) objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key) objc_removeAssociatedObjects(id _Nonnull object)
id object 被关联的对象
const void *key 关联的key,唯一
id value 关联的对象
objc_AssociationPolicy policy 内存管理的策略
remove 移除一个管理对象
@property (nonatomic, copy) NSString *cid; - (void)setCid:(NSString *)cid { objc_setAssociatedObject(self, &kStringKey, cid, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (NSString *)cid { return objc_getAssociatedObject(self, &kStringKey); }
2、为UIButton类别添加点击block
// UIButton+Block.h typedef void (^ButtonBlock)(id sender); - (void)handleWithBlock:(ButtonBlock)block; // UIButton+Block.m static const char kButtonKey; - (void)handleWithBlock:(ButtonBlock)block { if (block) { // objc_setAssociatedObject(self, @selector(btnAction:), block, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &kButtonKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } [self addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside]; } - (void)btnAction:(id)sender { // ButtonBlock block = objc_getAssociatedObject(self, @selector(btnAction:)); ButtonBlock block = objc_getAssociatedObject(self, &kButtonKey); if (block) { block(sender); } }