iOS之关联引用 Associate

1.给分类category添加属性

#import "Person.h"

@interface Person (AssocRef)

@property (nonatomic, strong) NSString *emailAddress;

@end


#import "Person+AssocRef.h"
#import <objc/runtime.h>

@implementation Person (AssocRef)

static char emailAddressKey;

//将emailAddress关联self对象,将值引用到emailAddressKey地址

-(NSString *)emailAddress
{
    return objc_getAssociatedObject(self, &emailAddressKey);
}

-(void)setEmailAddress:(NSString *)emailAddress
{
    objc_setAssociatedObject(self, &emailAddressKey, emailAddress, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


- (void)viewDidLoad {
    [super viewDidLoad];
    Person *p = [[Person alloc] init];
    
    p.emailAddress = @"2";
    
    NSLog(@"%@",p.emailAddress);

}


2.测试类

#import "Person.h"
@implementation Person
-(void)dealloc
{
    NSLog(@"xxxx delloc");
}

//会将Person引用到kWatcherKey,关联someting,当someting销毁的时候,Person也会销毁,然后会调用person的delloc方法
static char kWatcherKey;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSObject *something = [NSObject new];
    objc_setAssociatedObject(something, &kWatcherKey, [Person new], OBJC_ASSOCIATION_RETAIN);
}


3.给警告框或控件附着相关对象的好办法

#import "ViewController.h"
#import <objc/runtime.h>

//作为中转地址使用
static char kPeprensentedObject;

@interface ViewController ()<UIAlertViewDelegate>

@end

@implementation ViewController

//将sender的地址关联alertView对象。然后再从alertView对象取出sender地址,即拿出当前的button

//能够将sender的地址引入kPeprensentedObject

- (IBAction)clickBtn:(UIButton *)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    
    objc_setAssociatedObject(alert,&kPeprensentedObject,sender,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [alert show];

    
}

//从kPeprensentedObject地址取出sender
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIButton *sender = objc_getAssociatedObject(alertView, &kPeprensentedObject);
    NSLog(@"%@",[[sender titleLabel] text]);
}


你可能感兴趣的:(iOS之关联引用 Associate)