我不确定如何解释这一点,但是我很肯定有一种方法可以做到这一点,但是我还没有得到。这是我的示例:我有10个变量(整数值),并使用该变量的值设置了字符串。
这是一个有关天气和云量的示例,用于确定天气状况:
if (hour1cloud <= 5) {
hour1weather = @"Clear";
}
if (5 < hour1cloud <= 25) {
hour1weather = @"Mostly Clear";
}
if (25 < hour1cloud <= 50) {
hour1weather = @"Partly Cloudy";
}
if (50 < hour1cloud <= 83) {
hour1weather = @"Mostly Cloudy";
}
if (83 < hour1cloud <= 105) {
hour1weather = @"Overcast";
}
假设我有hour2cloud,hour3cloud,hour4cloud等,它们对应于hour2weather,hour3weather等。有什么方法可以使我成为通用方法,只需输入hour1cloud并检索hour1weather?
最佳答案
为什么不写这样的方法:
- (NSString*)weatherStringFromCloud:(int)cloud {
NSString *weather;
if (cloud <= 5) {
weather = @"Clear";
} else if (cloud <= 25) {
weather = @"Mostly Clear";
} else if (cloud <= 50) {
weather = @"Partly Cloudy";
} else if (cloud <= 83) {
weather = @"Mostly Cloudy";
} else if (cloud <= 105) {
weather = @"Overcast";
} else {
weather = nil;
}
return weather;
}
然后使用各种值进行调用:
hour1weather = [self weatherStringFromCloud:hour1cloud];
hour2weather = [self weatherStringFromCloud:hour2cloud];
hour3weather = [self weatherStringFromCloud:hour3cloud];
hour4weather = [self weatherStringFromCloud:hour4cloud];
关于iphone - 如何重复使用不同变量的 Action ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13126989/