以下代码使用了三种不同的的方法实现了条件判断,分别为if、switch、map的形式。前两者实现起来简单,但是会遇到两个问题:1、在条件实现里面堆砌大量代码,增加阅读上面的难度。2、判断时间过长,假如有n个条件,可能就要判断n次。
1、假如能够将条件实现里面的代码抽出来,可以降低阅读难度。解决问题1
2、if、switch无法解决问题2,但是通过map的方式能够解决问题2.
- (IBAction)click:(id)sender {
UIButton *button = (UIButton *)sender;
NSInteger tag = button.tag;
//在这里假设tag值是条件,button是参数
//根据参数,实现具体的业务逻辑,这里举例打印button的标题,现实中可能会做各种不同的业务逻辑:拿到button的图片、更新button的点击状态等
if (tag==1) {
NSLog(@"if条件判断%@", button.currentTitle);
}
if (tag==2) {
NSLog(@"if条件判断%@", button.currentTitle);
}
if (tag==3) {
NSLog(@"if条件判断%@", button.currentTitle);
}
if (tag==4) {
NSLog(@"if条件判断%@", button.currentTitle);
}
if (tag==5) {
NSLog(@"if条件判断%@", button.currentTitle);
}
NSLog(@"启用缺省逻辑");
switch (tag) {
case 1:
NSLog(@"switch条件判断%@", button.currentTitle);
break;
case 2:
NSLog(@"switch条件判断%@", button.currentTitle);
break;
case 3:
NSLog(@"switch条件判断%@", button.currentTitle);
break;
case 4:
NSLog(@"switch条件判断%@", button.currentTitle);
break;
case 5:
NSLog(@"switch条件判断%@", button.currentTitle);
break;
default:
NSLog(@"启用缺省逻辑");
break;
}
NSDictionary *dict = @{
@"1":@"clickButton1:",
@"2":@"clickButton2:",
@"3":@"clickButton3:",
@"4":@"clickButton4:",
@"5":@"clickButton5:"
};
//key对应的判断条件,value对应执行方法的名字
NSString *methodStr = dict[@(tag).stringValue];
SEL method = nil;
if (methodStr == NULL) {
method = NSSelectorFromString(@"methodHolderplace");
} else {
method = NSSelectorFromString(methodStr);
}
//拿到参数
[self performSelector:method withObject:button];
}
- (void)methodHolderplace {
NSLog(@"启用缺省逻辑");
}
- (void)clickButton1:(UIButton *)sender {
NSLog(@"map条件判断%@", sender.currentTitle);
}
- (void)clickButton2:(UIButton *)sender {
NSLog(@"map条件判断%@", sender.currentTitle);
}
- (void)clickButton3:(UIButton *)sender {
NSLog(@"map条件判断%@", sender.currentTitle);
}
- (void)clickButton4:(UIButton *)sender {
NSLog(@"map条件判断%@", sender.currentTitle);
}
网友评论