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]);
}
相關文章
相關標籤/搜索