Common functions in the game when saving game data. cocos2dx provides us with the ccuserdefault class. This class uses XML files to store data and provides several basic storage interfaces.
// Obtain the specified value based on the key. The default value bool getboolforkey (const char * pkey) returned by the overloaded version is not read; bool getboolforkey (const char * pkey, bool defaultvalue ); int getintegerforkey (const char * pkey); int getintegerforkey (const char * pkey, int defaultvalue); float getfloatforkey (const char * pkey, float defaultvalue); double getdoubleforkey (const char * pkey, double defaultvalue); STD: String getstringforkey (const char * pkey); STD :: string getstringforkey (const char * pkey, const STD: string & defaultvalue); // set the value void setboolforkey based on the key (const char * pkey, bool value ); void setintegerforkey (const char * pkey, int value); void setfloatforkey (const char * pkey, float value); void setdoubleforkey (const char * pkey, double value ); void setstringforkey (const char * pkey, const STD: string & value); // call void flush () to save it to an XML file ();
The following is a simple test code, which can be directly put in the init method of helloworldscene. cpp.
CCUserDefault::sharedUserDefault()->setBoolForKey("isMax",false); CCUserDefault::sharedUserDefault()->setDoubleForKey("HP",2.0); CCUserDefault::sharedUserDefault()->setFloatForKey("MP",3.0f); CCUserDefault::sharedUserDefault()->setIntegerForKey("lv",2); CCUserDefault::sharedUserDefault()->setStringForKey("name","hjs"); bool ismax = CCUserDefault::sharedUserDefault()->getBoolForKey ("isMax" ); double hp = CCUserDefault::sharedUserDefault()->getDoubleForKey ("HP" ); float mp = CCUserDefault::sharedUserDefault()->getFloatForKey ("MP" ); int lv = CCUserDefault::sharedUserDefault()->getIntegerForKey("lv" ); std::string name = CCUserDefault::sharedUserDefault()->getStringForKey ("name" ); if(ismax) CCLOG("ismax true"); else CCLOG("ismax false"); CCLOG("hp:%f",hp); CCLOG("mp:%f",mp); CCLOG("lv:%d",lv); CCLOG("name:%s",name.c_str()); int tmp = CCUserDefault::sharedUserDefault()->getIntegerForKey("tmp",10); CCLOG("tmp:%d",tmp);
During the test, we found that the flush () method can be written to the XML file in time without calling it, but remember to call it.