0
votes

I have a basic misunderstanding of pointers thing . I want to create many sprites, and i want them to be known to all class . What i did-and its kind of a miracle that it works is this :

I defined in the .h file :CCSprite *brokenBox; , so all class can see him. Later , i have a function that create many of him , and add a body to each one .

-(void)someF
{

    brokenBox=[CCSprite spriteWithFile:@"brokenBox.png"];
    brokenBox.tag=5;
    brokenBox.position=ccp(point.x*relativeX, point.y );
    //now attach abody to him
    ....
    ....
    [self addChild:brokenBox];


}

Now this function is being called many times (many boxes are here). What i dont understand is how can a single pointer change the file it points on again and again, and how is that i can add him as a child again and again ? Does he creates many pointers ?

What is the correct way to work so i can have access to all these sprites ? (now to access them i do : [self getChildByTag:5]; and they all have the same tag=5.

Thanks a lot .

1

1 Answers

1
votes

The pointer brokenBox is changed every time you create a sprite. Thus, after you are done creating your 'many' sprites, brokenBox points to the last sprite you created.

getChildByTag only returns the first one it encounters in the children's list with the tag you gave. You probably want to have something like this :

in .h

NSNutableArray *_brokenBoxes;

@property (nonatomic,readonly) NSArray *brokenBoxes;
// remove your property for brokenBox, it would be invalid (see above)

in .m,

global

@synthesize brokenBoxes = _brokenBoxes;

init

_brokenBoxes = [[NSMutableArray array] retain];

dealloc

[_brokenBoxes release];

cleanup :

[_brokenBoxes removeAllObjects];

someF :

CCSprite *brokenBox=[CCSprite spriteWithFile:@"brokenBox.png"];
....
....
[brokenBoxes addObject:brokenBox];
[self addChild:brokenBox];

From your other classes, access your sprites with the array brokenBoxes.

for (CCSprite *brokenBox in self.brokenBoxes) {
    // do your stuff.
}