OC中的NSString
是無(wú)法直接帶入switch語(yǔ)句
中使用的慕爬,但是相比于使用if... else if語(yǔ)句
進(jìn)行判斷漓帚,個(gè)人還是偏向于使用switch語(yǔ)法
進(jìn)行編碼飘弧,所以為了讓NSString
可以和switch語(yǔ)句
結(jié)合使用携栋,可以使用一種間接的方法
這邊我會(huì)以一個(gè)例子舉例柳刮,比如當(dāng)我要處理多個(gè)NSComboBox
的內(nèi)容的時(shí)候挖垛,原先使用if...else if語(yǔ)句
的代碼如下所示(具體的NSComboBox的實(shí)現(xiàn)方式請(qǐng)看其它博主的詳情教程,這邊只貼出一部分代碼)
- (void)viewDidLoad {
[super viewDidLoad];
self.yearArr = @[@"1994",@"1995",@"1996"];
self.monthArr = @[@"1",@"2",@"3"];
self.dayArr = @[@"29",@"30",@"31"];
}
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)comboBox {
NSInteger num = 0;
if ([comboBox.identifier isEqualToString:@"year"]) {
num = [self.yearArr count];
} else if ([comboBox.identifier isEqualToString:@"month"]) {
num = [self.monthArr count];
} else if ([comboBox.identifier isEqualToString:@"day"]) {
num = [self.dayArr count];
}
return num;
}
- (nullable id)comboBox:(NSComboBox *)comboBox objectValueForItemAtIndex:(NSInteger)index {
NSString *content;
if ([comboBox.identifier isEqualToString:@"year"]) {
content = [self.yearArr objectAtIndex:index];
} else if ([comboBox.identifier isEqualToString:@"month"]) {
content = [self.monthArr objectAtIndex:index];
} else if ([comboBox.identifier isEqualToString:@"day"]) {
content = [self.dayArr objectAtIndex:index];
}
return content;
}
使用NSString
與switch語(yǔ)句
結(jié)合的方式秉颗,其實(shí)就是將要使用到的字符串到加入到一個(gè)數(shù)組中痢毒,然后再使用數(shù)組中的indexOfObject
方法獲取到一個(gè)NSUInteger
變量,這樣就可以配合switch語(yǔ)句
了
- (void)viewDidLoad {
[super viewDidLoad];
self.yearArr = @[@"1994",@"1995",@"1996"];
self.monthArr = @[@"1",@"2",@"3"];
self.dayArr = @[@"29",@"30",@"31"];
self.comboBoxID = @[@"year",@"month",@"day"];
}
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)comboBox {
NSInteger num = 0;
NSUInteger strIndex = [self.comboBoxID indexOfObject:comboBox.identifier];
switch (strIndex) {
case 0:
num = [self.yearArr count];
break;
case 1:
num = [self.monthArr count];
break;
case 2:
num = [self.dayArr count];
break;
}
return num;
}
- (nullable id)comboBox:(NSComboBox *)comboBox objectValueForItemAtIndex:(NSInteger)index {
NSString *content;
NSUInteger strIndex = [self.comboBoxID indexOfObject:comboBox.identifier];
switch (strIndex) {
case 0:
content = [self.yearArr objectAtIndex:index];
break;
case 1:
content = [self.monthArr objectAtIndex:index];
break;
case 2:
content = [self.dayArr objectAtIndex:index];
break;
}
return content;
}
再進(jìn)一步蚕甥,switch語(yǔ)句
中的這些0哪替、1、2的數(shù)字菇怀,這種方式的編碼可讀性不是太好凭舶,所以可以再結(jié)合枚舉
的方式晌块,首先先寫(xiě)個(gè)枚舉變量comboBoxIDType
,如下所示:
typedef NS_ENUM(NSUInteger, comboBoxIDType) {
year = 0,
month = 1,
day = 2
};
其它的代碼小改即可帅霜,此次只貼一部分匆背,其余相似的代碼一并照樣改即可:
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)comboBox {
NSInteger num = 0;
comboBoxIDType id = [self.comboBoxID indexOfObject:comboBox.identifier];
switch (id) {
case year:
num = [self.yearArr count];
break;
case month:
num = [self.monthArr count];
break;
case day:
num = [self.dayArr count];
break;
}
return num;
}