OC高效率52之在既有类中使用关联对象存放自定义数据

#import "ViewController.h"
#import <objc/runtime.h>
//objc_AssociationPolicy  枚举  对应等效的属性
static void *EocMyAlertViewKey = @"EocMyAlertViewKey";

@interface ViewController ()<UIAlertViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view, typically from a nib.
    //管理关联对象的方法
//    objc_setAssociatedObject(id object, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)设置关联对象值
//    objc_getAssociatedObject(id object, <#const void *key#>)获取关联对象值
//    objc_removeAssociatedObjects(<#id object#>) 移除指定对象的所有关联对象
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(200, 200, 100, 200)];
    button.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)action
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Question" message:@"What do you want to do" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
    
    void (^block)(NSInteger) = ^(NSInteger buttonIndex){
    
        if (buttonIndex == 0 ){
            [self doCancel:alert];
        }
        else
        {
            [self doContinue];
        }
    };
    //1.定义关联对象时 可指定内存管理语义,用以模仿定义属性所采用的“拥有关系”与“非拥有关系”
    objc_setAssociatedObject(alert, EocMyAlertViewKey, block,OBJC_ASSOCIATION_COPY);

    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //2.经过关联对象机制把两个对象连起来
    void (^block)(NSInteger) = objc_getAssociatedObject(alertView, EocMyAlertViewKey);
    block(buttonIndex);

    //3.只有在其余作法不可行时才应选用关联对象,由于这种方法一般会引入难以查找的bug
}
-(void)doCancel:(UIAlertView *)alert
{
    NSLog(@"Calcel");
    objc_removeAssociatedObjects(alert);
}

-(void)doContinue
{
    NSLog(@"doContinue");

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相关文章
相关标签/搜索