以下代碼使用了三種不同的的方法實(shí)現(xiàn)了條件判斷,分別為if胧沫、switch昌简、map的形式。前兩者實(shí)現(xiàn)起來(lái)簡(jiǎn)單绒怨,但是會(huì)遇到兩個(gè)問(wèn)題:1纯赎、在條件實(shí)現(xiàn)里面堆砌大量代碼,增加閱讀上面的難度南蹂。2犬金、判斷時(shí)間過(guò)長(zhǎng),假如有n個(gè)條件六剥,可能就要判斷n次晚顷。
1、假如能夠?qū)l件實(shí)現(xiàn)里面的代碼抽出來(lái)疗疟,可以降低閱讀難度该默。解決問(wèn)題1
2、if策彤、switch無(wú)法解決問(wèn)題2栓袖,但是通過(guò)map的方式能夠解決問(wèn)題2.
- (IBAction)click:(id)sender {
UIButton *button = (UIButton *)sender;
NSInteger tag = button.tag;
//在這里假設(shè)tag值是條件,button是參數(shù)
//根據(jù)參數(shù)店诗,實(shí)現(xiàn)具體的業(yè)務(wù)邏輯裹刮,這里舉例打印button的標(biāo)題,現(xiàn)實(shí)中可能會(huì)做各種不同的業(yè)務(wù)邏輯:拿到button的圖片、更新button的點(diǎn)擊狀態(tài)等
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對(duì)應(yīng)的判斷條件庞瘸,value對(duì)應(yīng)執(zhí)行方法的名字
NSString *methodStr = dict[@(tag).stringValue];
SEL method = nil;
if (methodStr == NULL) {
method = NSSelectorFromString(@"methodHolderplace");
} else {
method = NSSelectorFromString(methodStr);
}
//拿到參數(shù)
[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);
}