cocos2d-x UserDefault

转自:http://blog.csdn.net/yanghuiliu/article/details/6912612

正在做项目中有很多游戏数据要保存,常见的玩家数据这些比较简单的可以用CCUserDefault。它是cocos2d-x用来存取基本数据类型用的。保存为XML文件格式。

主要方法:(和java的map很像,键值对,应该很容易懂的)

void    setBoolForKey(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);

通过键读取数据,如果键不存在,可以设置一个defaultValue返回自己想要的值。

bool    getBoolForKey(const char* pKey, bool defaultValue = false);
int    getIntegerForKey(const char* pKey, int defaultValue = 0);
float    getFloatForKey(const char* pKey, float defaultValue=0.0f);
double    getDoubleForKey(const char* pKey, double defaultValue=0.0);
std::string    getStringForKey(const char* pKey, const std::string & defaultValue = "");

首次运行程序时可以去生成xml文件CCUserDefault::sharedUserDefault()->setIntegerForKey("MyGold", 0);

这样就可以生成一个xml文件。不过这种硬代码我不是很喜欢。

 

每次调用的时候要写很长的代码。可以建议搞几个宏,毕竟CCUserDefault的get,set实在太长了。

#define SaveStringToXML CCUserDefault::sharedUserDefault()->setStringForKey

#define SaveIntegerToXML CCUserDefault::sharedUserDefault()->setIntegerForKey

#define SaveBooleanToXML CCUserDefault::sharedUserDefault()->setBoolForKey

#define LoadStringFromXML CCUserDefault::sharedUserDefault()->getStringForKey

#define LoadIntegerFromXML CCUserDefault::sharedUserDefault()->getIntegerForKey

#define LoadBooleanFromXML CCUserDefault::sharedUserDefault()->getBoolForKey

如何首次生成判断文件是否存在呢

其实可以利用get方法去获取。 

if ( !LoadBooleanFromXML("_IS_EXISTED")) 
{
       initUserData();             
       SaveBooleanToXML("_IS_EXISTED", true);
}
原文地址:https://www.cnblogs.com/sevenyuan/p/3182850.html