我们可以在if - else条件下使用(id)吗?

时间:2010-04-06 06:49:21

标签: objective-c cocos2d-iphone

我在cocos2d中以下列方式编写了代码。

id actionTo = [CCFadeOut actionWithDuration:4.0f];  
id actionTo0 = [CCSequence actionWithDuration:2.0f];
if (m < enemyNumber)
    id actionTo1 = [CCCallFunc actionWithTarget:self selector:@selector(goToNextScene)];
else
    id actionTo1 = [CCCallFunc actionWithTarget:self selector:@selector(goToEndScene)];
id actionSeq = [CCSequence actions:actionTo, actionTo0, actionTo1, nil];
[targetE runAction: [CCSequence actions:actionSeq, nil]];  

error: expected expression before 'id'  

我收到了上述错误。我们不应该在if条件下使用(id)吗? 我希望通过使用if-else条件来调用两个选择器。 我该怎么做? 谢谢。

2 个答案:

答案 0 :(得分:6)

您无法在该位置声明新变量。你应该做的是在if-condition之前声明你的actionTo1变量并在那里设置它的值:

...
id actionTo1 = nil;
if (m < enemyNumber)
    actionTo1 = [CCCallFunc actionWithTarget:self selector:@selector(goToNextScene)];
else
    actionTo1 = [CCCallFunc actionWithTarget:self selector:@selector(goToEndScene)];
...

答案 1 :(得分:4)

编写

更简单
id actionTo1 = [CCCallFunc actionWithTarget:self selector:
                (m<energyNumber ? @selector(goToNextScene) : @selector(goToEndScene))];