学习笔记:通过 objc_setAssociatedObject alert 和 button关联 及传值




//唯一静态变量key

static const char associatedkey;

static const char associatedButtonkey;


- (IBAction)sendAlert:(id)sender

{

    

    NSString *message =@"我知道你是按钮了";

    

    UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"我要传值·" delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:nil];

    alert.delegate =self;

    [alert show];


     //#import <objc/runtime.h>头文件

     //objc_setAssociatedObject需要四个参数:源对象,关键字,关联的对象和一个关联策略。


     //1 源对象alert

    //2 关键字 唯一静态变量key associatedkey

    //3 关联的对象 sender

    //4 关键策略  OBJC_ASSOCIATION_RETAIN_NONATOMIC

    

    

    objc_setAssociatedObject(alert, &associatedkey, message,OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    

    objc_setAssociatedObject(alert, &associatedButtonkey, sender,OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    

}

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

{

    

    

    //通过 objc_getAssociatedObject获取关联对象

    NSString  *messageString =objc_getAssociatedObject(alertView, &associatedkey);

    

    

    UIButton *sender = objc_getAssociatedObject(alertView, &associatedButtonkey);

    

    _labebutton.text = [[sendertitleLabel]text];

    _ThisLabel.text = messageString;

    

    

    //使用函数objc_removeAssociatedObjects可以断开所有关联。通常情况下不建议使用这个函数,因为他会断开所有关联。只有在需要把对象恢复到原始状态的时候才会使用这个函数。

}

demo http://download.csdn.net/detail/lengshengren/6594365

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值