您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x CCUserDefault 实现数据存储XML

2014-10-16 10:07 411 查看
自带的存储

CCUserDefault *save=CCUserDefault::sharedUserDefault();

save->setBoolForKey("bool_value",true);

save->setDoubleForKey("double_value",0.1);

save->setFloatForKey("float_value",0.1f);

save->setIntegerForKey("integer_value",1);

save->setStringForKey("string_value","test");

save->flush();

自带的这个存储很简单,设置用set ,获取使用get

例如:

获取: CCUserDefault::sharedUserDefault()->getStringForKey("hello");

设置: CCUserDefault::sharedUserDefault()->setStringForKey("hello","world");

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

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

[cpp] view
plaincopy

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返回自己想要的值。

[cpp] view
plaincopy

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实在太长了。

[cpp] view
plaincopy

#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方法去获取。

[cpp] view
plaincopy

if ( !LoadBooleanFromXML("_IS_EXISTED"))



{



initUserData();



SaveBooleanToXML("_IS_EXISTED", true);



}

对了,ccUserDefault在0.9.1版本会在安卓平台下crash掉,更新源代码就OK了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: