for-loopcocos2d-iphonensmutablearraysigabrtccnode

Add CCNodes to a Parent CCNode using a for loop


-(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; 
}

I want to add CCNodes from fieldArray on to a parent CCNode "stackNode". When I use breakpoints I am able to add the CCNode at index 0 and CCNode at index 1. However the program crash at i=2. The error I receive is:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'child already added to another node. It can't be added again'

Before the crash "stackNode" has two children. I'm not adding the CCNodes one by one because I have hundreds of different arrays with many a fieldArray.count around 20. Please help I can explain more if I have been unclear.


Solution

  • Change the for loop start as follows :

    //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
    

    Also, in the code that creates fieldArray, make certain you have logic to ensure that there are no duplicates, otherwise you will have the same issue (but for an altogether different reason).