2-2 关联对象

0.分类无法添加成员变量 但是可以添加属性。 但是同样也没有成员变量

1.将一个key 和一个对象关联起来

怎么给分类 添加属性呢?
虽然我们声明了属性方法 但是系统只会申明方法但是不会给我们实现get set方法 怎么办呢。我们自己实现一个
主要还是runtime的时候才会添加进类里面。所以才可以使用runtime方法来实现
但是类扩展是变异阶段就添加进去了。编译的时候系统会报错

#import "UITabBarController+Custom.h"
#import 

///>  如何在.m里面添加属性
@interface UITabBarController (_ Custom)
////> 
@property (nonmatic, strong)  UIView *customTabbar;
@end
@implementation UITabBarController (_ Custom)
@end

@implementation UITabBarController (Custom)

- (void)setCustomTabbar:(UIView *)customTabbar {
    //这里使用方法的指针地址作为唯一的key
    objc_setAssociatedObject(self, @selector(customTabbar), customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)customTabbar {
    return objc_getAssociatedObject(self, @selector(customTabbar));
}

//其他方法...
1. static const char name;
  objc_setAssociatedObject(self, &name, customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2.static conat void *WJName;
  objc_setAssociatedObject(self, & WJName, customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
3.  objc_setAssociatedObject(self, @"name", customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

OC 中常量是保存在常量区。地址是不会变的
@end


实现的原理 保存在全局的HashMap当中 

 对象地址:Map. -->  @"name" :值

当我们对象销毁的时候 这个Map也会销毁

2.添加私有成员变量

给button添加block回调

@interface UIButton (Callback)

- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *))callbackBlock;

@end

@interface UIButton ()

@property (nonatomic, copy) void (^callbackBlock)(UIButton * button);

@end

@implementation UIButton (Callback)

- (void (^)(UIButton *))callbackBlock {
    return objc_getAssociatedObject(self, @selector(callbackBlock));
}

- (void)setCallbackBlock:(void (^)(UIButton *))callbackBlock {
    objc_setAssociatedObject(self, @selector(callbackBlock), callbackBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *))callbackBlock {
    
    if (self = [super initWithFrame:frame]) {
        self.callbackBlock = callbackBlock;
        [self addTarget:self action:@selector(didClickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)didClickAction:(UIButton *)button {
    self.callbackBlock(button);
}

@end

你可能感兴趣的:(2-2 关联对象)