有没有更好的方法来编写这个Objective-c代码?

时间:2010-10-27 02:17:34

标签: iphone objective-c cocos2d-iphone

当我更改场景时,此代码会创建一个随机过渡。有十一个过渡。因为它们是静态的,我想我不能使用NSClassFromString。我还需要传递场景对象。 现在,交换机似乎是多余的。有没有办法重写这个以提高效率?

-(void) newScene
{
CCScene *s = [CCScene node];
id child = [sceneCharacter node];
[s addChild:child];
int random = arc4random() % 10;


switch (random)
{
    case 1:
        [[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 2:
        [[CCDirector sharedDirector] replaceScene:[CCFadeTRTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 3:
        [[CCDirector sharedDirector] replaceScene:[CCJumpZoomTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 4:
        [[CCDirector sharedDirector] replaceScene:[CCMoveInLTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 5:
        [[CCDirector sharedDirector] replaceScene:[CCOrientedTransitionScene transitionWithDuration:0.5f scene:s]];
        break;

    case 6:
        [[CCDirector sharedDirector] replaceScene:[CCPageTurnTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 7:
        [[CCDirector sharedDirector] replaceScene:[CCRotoZoomTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 8:
        [[CCDirector sharedDirector] replaceScene:[CCShrinkGrowTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 9:
        [[CCDirector sharedDirector] replaceScene:[CCSlideInLTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 10:
        [[CCDirector sharedDirector] replaceScene:[CCSplitColsTransition transitionWithDuration:0.5f scene:s]];
        break;

    case 0:
        [[CCDirector sharedDirector] replaceScene:[CCTurnOffTilesTransition transitionWithDuration:0.5f scene:s]];
        break;

    default:
        [[CCDirector sharedDirector] replaceScene:s];
}

}

3 个答案:

答案 0 :(得分:6)

您可以将所有CC * Transition对象放入一个数组中,并使用随机数索引该数组:

transition tt = transitions[random];
[[CCDirector sharedDirector] replaceScheme:[tt transitionWithDuration: 0.5f scene:s]];

另外警告,你的随机数只会取0到9之间的值。如上所述,情况10,默认情况永远不会发生。

答案 1 :(得分:2)

最少的代码和奢侈的内存使用情况:

NSArray *sceneClasses = [[NSArray arrayWithObjects:[CCFadeTransition class],
                                                   [CCFadeTRTransition class],
                                                   /*the whole list of 
                                                   transition types*/
                                                   nil] retain];

[[CCDirector sharedDirector] replaceScene:[[sceneClasses objectAtIndex:random] transitionWithDuration: 0.5f scene:s]];

答案 2 :(得分:1)

在switch语句之后只分配变量s并执行整个调用怎么样,因为你唯一的问题是冗余?像:

case 1:;
    s = [CCFadeTransition transitionWithDuration:0.5f scene:s]];
    break;

然后在switch语句后调用replaceScene:

[[CCDirector sharedDirector] replaceScene:s];
恕我直言,那更干净。