使用关联对象存放自定义数据

一、关联的形式

使用关联对象存放自定义数据_第1张图片
关联的形式

二、关联方法

使用关联对象存放自定义数据_第2张图片
关联方法解释

三、关联举例

下面已我们常见的UIAlertView进行举例说明
直接给出代码

#import "ViewController.h"
#import 


static void *PHMyAlertViewKey = @"PHMyAlertViewKey";

@interface ViewController ()

@end

@implementation ViewController 

- (void)viewDidLoad {
    [super viewDidLoad];

    {
        UIButton *butt = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 50, 25)];
        [butt setTitle:@"alert" forState:UIControlStateNormal];
        [butt setBackgroundColor:[UIColor cyanColor]];
        [butt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [butt addTarget:self action:@selector(addAlert) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:butt];
    }    


    {
        UIButton *butt = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 50, 25)];
        [butt setTitle:@"alert1" forState:UIControlStateNormal];
        [butt setBackgroundColor:[UIColor cyanColor]];
        [butt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [butt addTarget:self action:@selector(addoneagain) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:butt];
    }
}

- (void)addAlert{
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question" message:@"choose one" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
    void (^block) (NSInteger) = ^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            NSLog(@"block cancel");
        } else {
            NSLog(@"block continue");
        }
    };
    //为这个alert保存了一个block值
    objc_setAssociatedObject(alert, PHMyAlertViewKey, block, OBJC_ASSOCIATION_COPY);
    
    [alert show];
}

- (void)addoneagain{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question" message:@"choose one again" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
    void (^block) (NSInteger) = ^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            NSLog(@"block cancel again");
        } else {
            NSLog(@"block continue again");
        }
    };
    
    objc_setAssociatedObject(alert, PHMyAlertViewKey, block, OBJC_ASSOCIATION_COPY);
    
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    void (^blcok) (NSInteger) = objc_getAssociatedObject(alertView, PHMyAlertViewKey);
    //执行方法
    blcok(buttonIndex);

    objc_removeAssociatedObjects(alertView);
}

在上面的alertView代理方法中只要写上需要执行的block就ok了,这样一来使得设置和执行的逻辑显示非常清晰,特别是对于一个页面要弹出多个alertview的时候很好用

四、提醒

使用关联对象存放自定义数据_第3张图片

附:文章内容来自于《Effective Objective-C 2.0》

你可能感兴趣的:(使用关联对象存放自定义数据)