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

一、关联的形式

关联的形式

二、关联方法

关联方法解释

三、关联举例

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

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


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的时候很好用

四、提醒

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容