Saturday 25 January 2014

How to use CCUserDefault in cocos2d-x

CCUserDefault acts as a key value pair and stores the values corresponding to the keys

Suppose you want to store a high score of your game so that when the user restarts the game after exiting, the changes persist.

Take a new cocos2d-x project
In your .cpp file in init function delete the lines after these lines
if(!CCLayer::init())
{
return false 
}   
up to the lines just above the return true statement.Don't delete the return true statement. 
Take a constant key value at the top after all your header inclusion.

 const char *HIGH_SCORE="key1"; 

key1 is a key and this key must be different for every const char * which you declare


Then in your init function just below the lines 
if(!CCLayer::init())
{
return false 
}   

write the following code

CCUserDefault *def=CCUserDefault::sharedUserDefault();
def-> setIntegerForKey(HIGH_SCORE, 2000);
def->flush();

Here def is a pointer to CCUserDefault and it will help to access all the methods in that class.SetIntegerForKey is the method which sets the corresponding integer value to the constant char *.There are many more functions to store string, float, bool and double values.

flush() is a function which flushes the contents to the xml file. It basically saves the data to the xml file

To retrieve values from the key,suppose we want to retrieve the high score and display on a label. Now write the following line

int high_score=def->getIntegerForKey(HIGH_SCORE);


Here we are converting the integer into a string so that we can display on a label
char s[2];
sprintf(s,"%d", high);

Adding the score to a label
CCLabelTTF *high_label=CCLabelTTF::create(s, "Arial.fnt", 20);
high_label->setPosition(ccp(200,200));
this->addChild(high_label);

Now run your project and you will see 2000 on the screen. Now stop the run and comment the following lines

//def->setIntegerForKey(HIGH_SCORE, 2000);
//def->flush();

Again re run the project and still the value is 2000 on the screen.It means that now HIGH_SCORE is stored in the xml file and the value is retrieved from it.Therefore the changes persist even after application is closed