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]);
}


转载于:https://my.oschina.net/u/2346786/blog/626867

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值