iOS runtime 關(guān)聯(lián)對(duì)象(Associated Object)

摘要

在不用繼承類(lèi)的情況下,可以通過(guò)“關(guān)聯(lián)對(duì)象” 機(jī)制來(lái)把兩個(gè)對(duì)象連起來(lái)。對(duì)已有類(lèi)添加屬性。

需求

同一個(gè)類(lèi)有多個(gè)alertView, 不同的alertView 點(diǎn)擊確定按鈕 執(zhí)行的方法不同

alertOne 點(diǎn)擊 確定按鈕 執(zhí)行 methodOne, alertTwo 點(diǎn)擊確定按鈕 執(zhí)行 methodTwo

常規(guī)做法

初始化并顯示 alertOne

-?(IBAction)showAlertOne:(id)sender?{????UIAlertView?*alertOne?=?[[UIAlertView?alloc]initWithTitle:@"AlertOne"message:@""delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",?nil];????[alertOnesetTag:1];????[alertOne?show];}

初始化并顯示alertTwo

-?(IBAction)showAlertTwo:(id)sender?{????UIAlertView?*alertTwo?=?[[UIAlertView?alloc]initWithTitle:@"AlertTwo"message:@""delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",?nil];????[alertTwosetTag:2];????[alertTwo?show];}

實(shí)現(xiàn)代理

-(void)alertView:(UIAlertView*)alertViewclickedButtonAtIndex:(NSInteger)buttonIndex{if(buttonIndex?==0)?{????????

? ? ?return;????

}if(alertView.tag?==1)?{if(buttonIndex?==1)?{[self?methodOne];????????}????}elseif(alertView.tag?==2)?{if(buttonIndex?==1)?{[self?methodTwo];????????}????}}

Associated Object 做法

import runtime.h,定義屬性關(guān)聯(lián)key

#import"ViewController.h"#importstaticvoid*alertViewKey?="alertViewKey";

初始化并顯示 alertOne,同時(shí)定義block,將block 與 alertOne 關(guān)聯(lián)

-?(IBAction)showAlertOne:(id)sender?{UIAlertView*alertOne?=?[[UIAlertViewalloc]initWithTitle:@"AlertOne"message:@""delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",nil];void(^block)(NSInteger)?=?^(NSIntegerbuttonIndex)?{if(buttonIndex?==1)?{????????????[selfmethodOne];????????}????};????objc_setAssociatedObject(alertOne,?alertViewKey,?block,?OBJC_ASSOCIATION_COPY);//將block?與?alertOne?關(guān)聯(lián)[alertOne?show];

初始化并顯示 alertTwo,同時(shí)定義block,將block 與 alertTwo 關(guān)聯(lián)

-?(IBAction)showAlertTwo:(id)sender?{UIAlertView*alertTwo?=?[[UIAlertViewalloc]initWithTitle:@"AlertTwo"message:@""delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",nil];void(^block)(NSInteger)?=?^(NSIntegerbuttonIndex)?{if(buttonIndex?==1)?{????????????[selfmethodTwo];????????}????};????objc_setAssociatedObject(alertTwo,?alertViewKey,?block,?OBJC_ASSOCIATION_COPY);????[alertTwo?show];}

實(shí)現(xiàn)代理,在代理方法中,直接取出當(dāng)前alert 所關(guān)聯(lián)上的 block,再將buttonIndex 傳入,讓block 自己調(diào)用對(duì)應(yīng)方法

-(void)alertView:(UIAlertView?*)alertView?clickedButtonAtIndex:(NSInteger)buttonIndex{????if(buttonIndex?==0){????????return;????}????void(^block)(NSInteger)=?objc_getAssociatedObject(alertView,?alertViewKey);????block(buttonIndex);}

比較

通過(guò)使用Associated object 方法有多個(gè)好處 :

簡(jiǎn)化代碼

讓代碼層次清晰

充分利用對(duì)象與屬性的擁有關(guān)系

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容