I hope you guys can help me, I’ve got a basic problem with populating an array with objects.
I created an array in the header file like this: CCArray * animations;
and then I tried to populate it with data:
@
AnimationClass * anim;
anim = new AnimationClass;
anim~~>numOfFrames = numFrames;
anim~~>numOfRounds = numOfRounds;
anim~~>tPerFrame = tPerFrame;
anim~~>filename = str;
this~~>animations~~>addObject(anim);@
The problem I have is that the object is overwritten. Each object references to the same anim-object.
How do I fix that?
I thought that you create an object by ObjectClass * obj = ObjectClass::create();
or ObjectClass * obj = new ObjectClass();
and then it should create a new instance which is unique, or am I missing something?
You must create a new object with “ObjectClass * obj = ObjectClass::create()”. This method return a pointer to the object.
Are you using some kind of iteration? I think that you are adding the same pointer that you overwrites in each iteration and then you have an array of pointers to the last object that you create.
Please, paste the full code.
I don’t think that this is the actual problem, it’s more that the object is released after adding it to the array.
I had to create a new class which contains some int values and a const char * string, like this:
animationclass.h
@ #include “cocos2d.h”
USING_NS_CC;
class AnimationClass: public CCObject {
private:
public:
const char * filename;
int numOfFrames;
int tPerFrame;
int numOfRounds;
int actualFrame;
int actualRound;
static AnimationClass * create();
};
@
You don’t need to implement copy(). I create my objects and populate arrays with them fine. There must be a problem in your code. I see no problem in what you posted so it’s somewhere else.
PS Okay another try: how did you create array you store in your class? if you created it as an autorelease object did you retain it afterwards?
It was a problem with stringstream, which I used to create the tags for the object.
What I did was the following:
@ tempString.str(“”);
tempString << textureName << “t_”;
this~~>addAnimation.c_str, 9, 0.08, 1);
tempString.str;
tempString << textureName << “r_”;
this~~>addAnimation(tempString.str().c_str(), 9, 0.08, 1);@
So the string which I generated was still changeable and not hard stored, by changing tempString it changed the string also in the array objects.
Is there a way to copy the string before passing it to the function, so that it’s constant?
The function addAnimation is like this: void AnimatedObject::addAnimation(const char * str, int numFrames, float tPerFrame, int numOfRounds) { AnimationClass * anim = new AnimationClass();//AnimationClass::create(); anim->numOfFrames = numFrames; anim->numOfRounds = numOfRounds; anim->tPerFrame = tPerFrame; anim->filename = str; this->animations->addObject(anim); printf("name: %s\r\n",anim->filename); }