一、简述
CCUserDefalt作为NS
UserDefalt类的cocos2d-x实现版本,承担了cocos2d-x引擎的记录实现功能。
他的接口非常简单。
bool getBoolForKey (const char *pKey, bool defaultValue=false)
//Get bool value by key, if the key doesn't exist, a default value will return.
int getIntegerForKey (const char *pKey, int defaultValue=0)
//Get integer value by key, if the key doesn't exist, a default value will return.
float getFloatForKey (const char *pKey, float defaultValue=0.0f)
//Get float value by key, if the key doesn't exist, a default value will return.
double getDoubleForKey (const char *pKey, double defaultValue=0.0)
//Get double value by key, if the key doesn't exist, a default value will return.
std::string getStringForKey (const char *pKey, const std::string &defaultValue="")
//Get string value by key, if the key doesn't exist, a default value will return.
void setBoolForKey (const char *pKey, bool value)
//Set bool value by key.
void setIntegerForKey (const char *pKey, int value)
//Set integer value by key.
void setFloatForKey (const char *pKey, float value)
//Set float value by key.
void setDoubleForKey (const char *pKey, double value)
//Set double value by key.
void setStringForKey (const char *pKey, const std::string &value)
//Set string value by key.
在helloworld中增加如下代码
01.CCUserDefault *save=CCUserDefault::sharedUserDefault();
02.save->setBoolForKey("bool_value",true);
03.save->setDoubleForKey("double_value",0.1);
04.save->setFloatForKey("float_value",0.1f);
05.save->setIntegerForKey("integer_value",1);
06.save->setStringForKey("string_value","test");
然后写入存档就完成了。
读取也很简单,用对应的get函数即可。但是,我不建议你使用get函数的缺省返回值,尤其是在没有生成存档的时候。
二、CCUserDefalt的问题
1.没有记录和表的概念
你会发现,如果要设置多存档,必须自己操作,而且代码会变得复杂,容易出错。
对于简单的游戏可以使用
CCUserDefalt,但是对于复杂游戏,可以考虑使用SQLite。
2.没有数据类型安全
比如,如果你
错写
把一个Integer按Bool读取,是没有错误提示的
3.没有存档数据完整性的校验
可以看到存档是明文的xml,如果玩家篡改了数据,你无从知晓。这个可以自己增加一个校验,比如crc,哈希之类的。
三、存档和游戏初始化的建议流程
一个建议的流程是:
01.if(!档案不存在)
02.{
03. 使用缺省数据写入存档;
04.}
05.读取存档并初始化数据;
这是我在开发时使用的,在没有存档时首先写入一个,然后再读取。这减小了编码量,保证主要流程清晰。
那么如何判断存档不存在呢?我之前想用标准c++的fstream函数,但是如果从CCUserDefalt中用getXMLFilePath获得存档路径的话。如果此时存档文件不存在,就会自动生成一个。所以接下来的判断存档是否存在代码就会失效了。
yanghuiliu的blog中提到了一个方法,我其实不建议使用这种缺省返回值的方式,但是cocos2dx就设计成这样了,所以可以使用这种方法。
01.CCUserDefault *save=CCUserDefault::sharedUserDefault();
02.if(save->getBoolForKey("isExisted"))
03.{
04. //相关操作
05. save->setBoolForKey("isExisted",true);
06.}
参考文献:
本文出自 “老G的小屋” 博客,请务必保留此出处http://goldlion.blog.51cto.com/4127613/770754