Srini
Srini

Reputation: 387

Cocos2D removeChildByTag

I am making my first cocos2D game and i had trouble in tag. i gonna add many sprite to my gamelayer so i used [self addChild:sprite z:1 tag:aTag]; where aTag +=1; each time i increase the tag value. because each sprite should have a unique tag value. sometime i wanna clear all the child in my gamelayer so i remove those sprite by using the tag value like this.

 for (int i=10; i<1000; i++) {
        CCNode *child = [self getChildByTag:i];

        if (child == nil)
            NSLog(@"removeChildByTag: child not found!");
        else{
            NSLog(@"child removed");
            [self removeChild:child cleanup:YES];
            child=nil;
        }
    }  

and when i add these sprite again like [self addChild:sprite z:1 tag:aTag] to my gamelayer there was error occured "EXE bad Access". why it show the error.

Upvotes: 1

Views: 3435

Answers (2)

9to5ios
9to5ios

Reputation: 5545

Use to define SAFE_REMOVE like this

#define SAFE_REMOVE(p)              if (p) [p removeFromParentAndCleanup:YES];


// Remove the the tag


CCNode* node = [self getChildByTag:YOURTAGNAMEHERE];
    if (node != nil)
    {
        SAFE_REMOVE(node);
    }

Upvotes: 0

Lim Gim Hong
Lim Gim Hong

Reputation: 306

you can directly remove a child by using
[self removeChildByTag:aTag cleanup:YES];

as for the bad access, check if sprite is empty or if the image is empty

Upvotes: 3

Related Questions