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

本文深入探讨了如何在Objective-C中利用关联对象和UIAlertView进行高级应用开发,包括如何设置、获取和移除关联对象值,以及如何在不同按钮点击事件中灵活调用自定义函数块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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


转载于:https://my.oschina.net/u/2319073/blog/607090

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值