使用for循环将CCNode添加到父CCNode

时间:2014-10-05 05:41:48

标签: for-loop cocos2d-iphone nsmutablearray sigabrt ccnode

-(CCNode *)createFieldNode:(NSMutableArray *)fieldArray{

    CGSize winSize = [CCDirector sharedDirector].viewSize;
    CCNode* stackNode= [CCNode node];

    for (int i; i <=fieldArray.count; i++){
        //itemP is previous item in array and itemC is current item in area based on index i 
        BPItem*itemP;
        BPItem*itemC;

        if(i!=0){
            itemP=[fieldArray objectAtIndex:i-1];
            itemC=[fieldArray objectAtIndex:i];
            float stackWidth=arc4random()%200+50; 
            float stackHeight=itemP.position.y+itemP.contentSize.height;
            itemC.position=ccp(stackWidth,stackHeight);
        }
        else{
            itemC=[fieldArray objectAtIndex:i];
            float stackWidth=arc4random()%200+50; 
            itemC.position=ccp(stackWidth,0);
        }

        //having trouble adding multiple nodes to stackNode
        [stackNode addChild:itemC];
    }

    return stackNode; 
}

我想将fieldArray中的CCNode添加到父CCNode“stackNode”。当我使用断点时,我能够在索引0处添加CCNode,在索引1处添加CCNode。但是程序在i = 2时崩溃。我收到的错误是:

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'child已添加到另一个节点。它不能再添加'

崩溃前“stackNode”有两个孩子。我不是逐个添加CCNode,因为我有数百个不同的数组,其中有很多fieldArray.count在20左右。如果我不清楚,请帮助我解释一下。

1 个答案:

答案 0 :(得分:1)

更改for循环开始,如下所示:

//itemP is previous item in array and itemC is current item in area based on index i 
BPItem*itemP;
BPItem*itemC;                             // moved out of the for loop
for (int i; i <fieldArray.count; i++){    // <- changed the end condition to avoid crash
   ... rest of loop

此外,在创建fieldArray的代码中,请确保您有逻辑以确保没有重复项,否则您将遇到相同的问题(但出于完全不同的原因)。