2012-02-22 103 views
3

任何人都知道我将如何减少我的以下几行代码?我在objective-c/cocos2D方面还是相当新的,我的下面的代码看起来像火车残骸。如果是PHP,我可以轻松创建一个循环来获取所有这些内容,但对于obj-c还不够熟悉,但尚未弄清楚。Objective-C/Cocos2D重复代码减少

dinosaur1_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur1-c.png"]; 
    dinosaur2_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur2-c.png"]; 
    dinosaur3_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur3-c.png"]; 
    dinosaur4_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur4-c.png"]; 
    dinosaur5_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur5-c.png"]; 
    dinosaur6_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur6-c.png"]; 
    dinosaur7_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur7-c.png"]; 
    dinosaur8_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur8-c.png"]; 
    dinosaur9_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur9-c.png"]; 
    dinosaur10_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur10-c.png"]; 
    dinosaur11_c = [CCSprite spriteWithSpriteFrameName:@"dinosaur11-c.png"]; 

    [sceneSpriteBatchNode addChild:dinosaur1_c]; 
    [sceneSpriteBatchNode addChild:dinosaur2_c]; 
    [sceneSpriteBatchNode addChild:dinosaur3_c]; 
    [sceneSpriteBatchNode addChild:dinosaur4_c]; 
    [sceneSpriteBatchNode addChild:dinosaur5_c]; 
    [sceneSpriteBatchNode addChild:dinosaur6_c]; 
    [sceneSpriteBatchNode addChild:dinosaur7_c]; 
    [sceneSpriteBatchNode addChild:dinosaur8_c]; 
    [sceneSpriteBatchNode addChild:dinosaur9_c]; 
    [sceneSpriteBatchNode addChild:dinosaur10_c]; 
    [sceneSpriteBatchNode addChild:dinosaur11_c]; 

任何输入不胜感激!

+1

是否'dinosaur1_c'你的实例变量,或者是他们临时变量? – dasblinkenlight 2012-02-22 03:41:04

+0

它们是实例变量 – rizzlerazzle 2012-02-22 04:32:40

回答

4

我建议管理这些对象与NSMutableArray,像这样:

NSMutableArray *sprites = [[NSMutableArray alloc] init]; 
for (int i = 1; i <= 11; i++) { 
    id dino = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"dinosaur%d-c.png",i]]; 
    [sprites addObject:dino]; 
    [sceneSpriteBatchNode addChild:dino]; 
} 

// Since I don't know what your addChild: method does, the 'sprites' array exists to let you access the objects later, outside of the 'for' loop if desired... 
// So where you would've used dinosaur4_c before, you would instead use [sprites objectAtIndex:4] 
// This also demonstrates how to cast the return value from -objectAtIndex: to a CCSprite * 
CCSprite *certainDino = (CCSprite *)[sprites objectAtIndex:4]; 

// Then, when done working with the sprites 
[sprites release]; 
+0

为什么不使用C数组(或CCArray)?它比链表更快。 – 2012-02-22 03:42:35

+0

你永远不会添加任何东西到'精灵' – 2012-02-22 03:43:55

+0

@JimRhodes谢谢;固定! – bneely 2012-02-22 03:45:18