【发布时间】:2014-11-07 09:48:39
【问题描述】:
我正在尝试创建一个函数来保存一些代码,但是我不知道该怎么做。
if (count > 100 && count < 120)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Time is up!"
message:[NSString stringWithFormat:@"You're really good at this! You scored %i points", count - 1]
delegate:self
cancelButtonTitle:@"Play Again"
otherButtonTitles:nil];
[alert show];
}
else if(count > 120)
{
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Time is up!"
message:[NSString stringWithFormat:@"TEACH ME MASTER, YOU'RE A GOD! You scored %i points", count - 1]
delegate:self
cancelButtonTitle:@"Play Again"
otherButtonTitles:nil];
[alert2 show];
}
else
{
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"Time is up!"
message:[NSString stringWithFormat:@"Not very good, you scored %i points", count - 1]
delegate:self
cancelButtonTitle:@"Play Again"
otherButtonTitles:nil];
[alert3 show];
}
如您所见,代码非常重复,我想创建一个函数来更改“alert”变量和消息字符串的值。因此,当我调用函数时,我只输入函数名称和警报变量应该具有的值,在这种情况下; 1、2 和 3 以及消息文本取决于我们正在查看的条件。
那么有什么方法可以做到这一点吗?必须有,因为像这样重复的代码永远不会好看!如果有人可以帮助我,我将不胜感激,我尝试查看一些参考资料,但没有一个能让我更接近解决问题。
【问题讨论】:
-
如果
count == 120,你就没有很好地处理这种情况。你应该做这样的事情:if (count < 100) { ... } else if (count < 120) { ... } else { ... },这将是处理三个分支的一种不那么模糊的方式。
标签: objective-c xcode function ios7