比使用If语句更高效的代码

时间:2014-02-15 09:05:16

标签: ios objective-c if-statement performance

我目前正在制作iOS应用程序将Objective-C。我有很多if语句使UIImageView出现在我的应用程序中。有没有更有效的方法来做,或者我应该保留所有的if语句?

由于

编辑 请参阅以下代码:

if (obscacle.center.x < 0) {
    randomPosition = arc4random() %20;
    randomPosition = randomPosition + 110;
    obscacle.center = CGPointMake(568, randomPosition);
}

if (obscacle2.center.x < 0) {
    randomPosition = arc4random() %20;
    randomPosition = randomPosition + 110;
    obscacle2.center = CGPointMake(568, randomPosition);
}


if (top1.center.x < -50) {
    randomPosition = arc4random() %20;
    top1.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom1.center = CGPointMake(568, randomPosition);
}

if (top2.center.x < -50) {
    randomPosition = arc4random() %20;
    top2.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom2.center = CGPointMake(568, randomPosition);
}

if (top3.center.x < -55) {
    randomPosition = arc4random() %20;
    top3.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom3.center = CGPointMake(568, randomPosition);
}

if (top3.center.x < -55) {
    randomPosition = arc4random() %20;
    top3.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom3.center = CGPointMake(568, randomPosition);
}

if (top4.center.x < -55) {
    randomPosition = arc4random() %20;
    top4.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom4.center = CGPointMake(568, randomPosition);
}

if (top5.center.x < -55) {
    randomPosition = arc4random() %20;
    top5.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom5.center = CGPointMake(568, randomPosition);
}

if (top6.center.x < -55) {
    randomPosition = arc4random() %20;
    top6.center = CGPointMake(550, randomPosition);
    randomPosition = randomPosition + 265;
    bottom6.center = CGPointMake(568, randomPosition);
}

if (top7.center.x < -55) {
    randomPosition = arc4random() %20;
    top7.center = CGPointMake(568, randomPosition);
    randomPosition = randomPosition + 265;
    bottom7.center = CGPointMake(568, randomPosition);
}

3 个答案:

答案 0 :(得分:4)

看起来你需要一些for循环。

伪代码:

for each obstacle in [array of obstacles]:
    if (obscacle.center.x < 0):
        randomPosition = arc4random() %20
        randomPosition = randomPosition + 110
        obscacle.center = CGPointMake(568, randomPosition)

同样适用于“顶级”。

请注意,这与效率无关,而是使代码更整洁,更易于维护。在性能方面,任何一种方法都应该超出您的使用范围。

答案 1 :(得分:0)

很难说没有看到你的代码,但由于某些原因,有时候switch语句是更好的替代。

示例:

switch (expression)
 {
     case match1:
          statements
          break;

     case match2:
          statements
          break;

     default:
          statements
          break;
 }

所有这些都取决于你想要做什么。

答案 2 :(得分:0)

根据您尝试做的事情,您可以完全消除if语句。

您说您正在使用if来选择要显示的图像。因此,如果您根据您在if中测试的变量命名图像,则可以改为使用该变量来选择正确的名称。