iOS中关联对象objc_setAssociatedObject的简单使用(传值使用)

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#import "wangmumu.h"

@interface wangmumu ()
{

}
@end

static char staticString;

@implementation SHVCarsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.tableView.hidden = YES;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor grayColor];
    [btn addTarget:self action:@selector(btnn:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(btn, &staticString, @"aaaa", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self.view addSubview:btn];
    
    
}

- (void)btnn:(UIButton *)btn{

    NSString *str = objc_getAssociatedObject(btn, &staticString);
    NSLog(@"%@",str);

}

/*
objc_setAssociatedObject(btn, &staticString, @"aaaa", OBJC_ASSOCIATION_RETAIN_NONATOMIC);

有四个参数
1.被关联的对象
2.要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
3.要传得值 一般是静态变量
4.关联时采用的协议,有assign,retain,copy等协议 点击进去选取枚举

*/