Is there a better way write this objective-c code?
this code creates a random transition when I change scenes. There are eleven transitions. Because they are static, I think I cannot use NSClassFromString. I also need to pass the scene (s) object. Right now the switch seems redundant. Is there a way to rewrite this to make it more efficient?
-(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];
}
}
You could put all of your CC*Transition objects into an array, and use the random number to index that array:
transition tt = transitions[random];
[[CCDirector sharedDirector] replaceScheme:[tt transitionWithDuration: 0.5f scene:s]];
Warning as an aside, your random number will only take on the values between 0 and 9. As written, case 10, and the default will never happen.
Least code and extravagant memory usage:
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]];
How about only assigning the variable s and doing the whole call after the switch statement since your only issue is redundancy? Like:
case 1:;
s = [CCFadeTransition transitionWithDuration:0.5f scene:s]];
break;
And then call replaceScene after the switch statement:
[[CCDirector sharedDirector] replaceScene:s];
IMHO, that's cleaner.
精彩评论