摘要
在不用继承类的情况下,可以通过“关联对象” 机制来把两个对象连起来。对已有类添加属性。
需求
同一个类有多个alertView, 不同的alertView 点击确定按钮 执行的方法不同
alertOne 点击 确定按钮 执行 methodOne, alertTwo 点击确定按钮 执行 methodTwo
常规做法
初始化并显示 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];}
实现代理
-(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,定义属性关联key
#import"ViewController.h"#importstaticvoid*alertViewKey ="alertViewKey";
初始化并显示 alertOne,同时定义block,将block 与 alertOne 关联
- (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 关联[alertOne show];
初始化并显示 alertTwo,同时定义block,将block 与 alertTwo 关联
- (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];}
实现代理,在代理方法中,直接取出当前alert 所关联上的 block,再将buttonIndex 传入,让block 自己调用对应方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if(buttonIndex ==0){ return; } void(^block)(NSInteger)= objc_getAssociatedObject(alertView, alertViewKey); block(buttonIndex);}
比较
通过使用Associated object 方法有多个好处 :
简化代码
让代码层次清晰
充分利用对象与属性的拥有关系