天天看点

objc_setAssociatedObject的用法,解决UIAlertView按钮传值问题

       我们在平时编程的时候,经常需要通过一些UIAlertView 向其他的类或者函数传递对象或者信息。点击某个button需要触发事件之后,需要把一些信息传递给响应的函数。但是却偏偏没有这样的参数去输入这些东西,objc_setAssociatedObject很好的解决了这个问题,从字面上来理解tAssociated就是协助object的类,或者说是附属在某个object的一个类。下面说下用法:

     说白了,就是通过objc_setAssociatedObject这个函数,把 UIAlertView和一个对象关联起来,具体这个函数怎么用的,我们来看看官方文档是怎么说的。

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
           

 Parameters

object

The source object for the association.//就是你需要绑定数据的那个类,这里面当然就是 UIAlertView啦

key

The key for the association.//因为一个 UIAlertView可以绑定多个对象,要通过这个key来找到相应的对象

value

The value to associate with the key key for object. Pass nil to clear an existing association.//需要和 UIAlertView绑定在一起的对象

policy

The policy for the association. For possible values, see Associative Object Behaviors. //绑定策略,具体都有哪些策略,参看 Associative Object Behaviors,这个就不多说了

具体怎么用,上段代码自然就明白了,原文出自http://blog.csdn.net/lengshengren/article/details/16886915/

之前需要引入

//#import <objc/runtime.h>头文件 
           
//唯一静态变量key
static const char associatedkey;
static const char associatedButtonkey;

- (IBAction)sendAlert:(id)sender
{
    
    NSString *message [email protected]"我知道你是按钮了";
    
    UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"我要传值·" delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.delegate =self;
    [alert show];

    
    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可以断开所有关联。通常情况下不建议使用这个函数,因为他会断开所有关联。只有在需要把对象恢复到“原始状态”的时候才会使用这个函数。
}