How to use CCArray in another class plz help me

hi

please give some information about CCArray i have one array in my first class i want use this array in second class,how can i use this array in another class plz help me

Regards

satish

Without proper information we really can’t help much. I assume you have a CCArray in one class and you want to use that CCArray in another class. What you want to do is to have this CCArray either public or have a public accessor for others to use. Assume our classes are named MyClassA and MyClassB. MyClassA would contain the CCArray.

// MyClassA.h
#include "cocos2d.h"
class MyClassA {
private:
   cocos2d::CCArray * m_MyArray;
public
   cocos2d::CCArray * getMyArray( ) { return m_MyArray; }
};

// MyClassB.h
#include "cocos2d.h"
class MyClassB {
public:
   void doSomethingWithArray( cocos2d::CCArray * p_Array );
};

// MyClassB.cpp
#include "MyClassB.h"
void MyClassB::doSomethingWithArray( cocos2d::CCArray * p_Array ) {
   // Do something with array.
   CCLOG( "MyClassB object got the array." );
}

Here comes the tricky part. There could be several ways on how you would access them. The simplest one is when the two objects are in a CCLayer.

MyClassA myObjA;
MyClassB myObjB;

myObjB.doSomethingWithArray( myObjA.getMyArray( ) );

Since the CCLayer holds the two objects together, you can just pass the MyClassA object to the method in MyClassB. The hard part is when you are accessing MyClassA from MyClassB itself and not in the CCLayer.

There are ways to do this:

  1. Create a singleton that will hold references to MyClassA and have MyClassB access that singleton.
  2. Pass a reference of MyClassA to MyClassB when you create an instance of MyClassB. This can be done by having a constructor that will accept a MyClassA object as parameter.
  3. Create a namespace that will hold the CCArray. Have other classes access that namespace when you want to use the CCArray.

thank u mr Lance Gray i think this is helpful to me.plz post sample code if u have?

Regards

satish

hi

my simple problem is i have one array in MyClass B that array contains names-us,india,japan,chaina etc ,

this is strings array i want to use this array in myClassA please post some sample code about this problem

Regards

satish

If you are using normal data types and not the cocos2d-x objects, it’s better to use std::vector. CCArray is only for cocos2d-x classes as it can only contain CCObject objects.