天天看點

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可以斷開所有關聯。通常情況下不建議使用這個函數,因為他會斷開所有關聯。隻有在需要把對象恢複到“原始狀态”的時候才會使用這個函數。
}