使用Runtime关联block简化多个Alertview的逻辑判断
对象关联
有的时候需要在对象中存放信息,这时候我们通常是是从对象所属的类中继承一个子类,然后改用这个子类。但有的情况无法创建自己的子类实例。这时候我们可以使用Object-C 中一项强大的特性,对象关联。
以下方法管理关联对象:
- void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) 此方法以给定的键和策略为某对象设置关联对象值。
-
id objc_getAssociatedObject(id object, const void *key) 此方法根据给定的键从某对象获取相应的关联对象值。
-
void objc_removeAssociatedObjects(id object) 此方法移除指定对象的全部关联对象。
下面用法举例:
当一个界面需要多个UIAlertView的时候,我们会添加很多逻辑判断,这时候我们可以用关联对象关联一个block来简化逻辑判断。
static void *alertidentifier= @"alertKey";
UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"title" message:@"提示信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[view show];
void (^block)(NSInteger) = ^(NSInteger buttonIndex){
if(buttonIndex==0){
NSLog(@"点击第一个UIAlertView:0");
}else{
NSLog(@"点击第一个UIAlertView:1");
}
};
objc_setAssociatedObject(view ,alertidentifier ,block ,OBJC_ASSOCIATION_COPY);
创建完警告视图之后,设定一个与之关联的block,等执行delegate方法时候再读出来。
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, alertidentifier);
block(buttonIndex);
}

浙公网安备 33010602011771号