且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

cocos2d-x学习笔记16:记录存储1:CCUserDefault

更新时间:2022-10-04 15:13:52

 cocos2d-x学习笔记16:记录存储1:CCUserDefault


一、简述
CCUserDefalt作为NSUserDefalt类的cocos2d-x实现版本,承担了cocos2d-x引擎的记录实现功能。

他的接口非常简单。

  1. bool    getBoolForKey (const char *pKey, bool defaultValue=false
  2.     //Get bool value by key, if the key doesn't exist, a default value will return.  
  3. int     getIntegerForKey (const char *pKey, int defaultValue=0) 
  4.     //Get integer value by key, if the key doesn't exist, a default value will return.  
  5. float   getFloatForKey (const char *pKey, float defaultValue=0.0f) 
  6.     //Get float value by key, if the key doesn't exist, a default value will return.  
  7. double  getDoubleForKey (const char *pKey, double defaultValue=0.0) 
  8.     //Get double value by key, if the key doesn't exist, a default value will return.  
  9. std::string     getStringForKey (const char *pKey, const std::string &defaultValue=""
  10.     //Get string value by key, if the key doesn't exist, a default value will return.  
  11. void    setBoolForKey (const char *pKey, bool value) 
  12.     //Set bool value by key.  
  13. void    setIntegerForKey (const char *pKey, int value) 
  14.     //Set integer value by key.  
  15. void    setFloatForKey (const char *pKey, float value) 
  16.     //Set float value by key.  
  17. void    setDoubleForKey (const char *pKey, double value) 
  18.     //Set double value by key.  
  19. void    setStringForKey (const char *pKey, const std::string &value) 
  20.     //Set string value by key.  

在helloworld中增加如下代码:

  1. CCUserDefault *save=CCUserDefault::sharedUserDefault(); 
  2. save->setBoolForKey("bool_value",true); 
  3. save->setDoubleForKey("double_value",0.1); 
  4. save->setFloatForKey("float_value",0.1f); 
  5. save->setIntegerForKey("integer_value",1); 
  6. save->setStringForKey("string_value","test"); 

然后写入存档就完成了。
 
读取也很简单,用对应的get函数即可。但是,我不建议你使用get函数的缺省返回值,尤其是在没有生成存档的时候。

二、CCUserDefalt的问题
1.没有记录和表的概念
你会发现,如果要设置多存档,必须自己操作,而且代码会变得复杂,容易出错。
对于简单的游戏可以使用CCUserDefalt,但是对于复杂游戏,可以考虑使用SQLite。

2.没有数据类型安全
比如,如果你错写把一个Integer按Bool读取,是没有错误提示的

3.没有存档数据完整性的校验
我们找到之前的存档记录,用CCUserDefault::getXMLFilePath()可以获得存档位置,打开它
cocos2d-x学习笔记16:记录存储1:CCUserDefault

可以看到存档是明文的xml,如果玩家篡改了数据,你无从知晓。这个可以自己增加一个校验,比如crc,哈希之类的。

三、存档和游戏初始化的建议流程

一个建议的流程是:

  1. if(!档案不存在) 
  2.      使用缺省数据写入存档; 
  3. 读取存档并初始化数据; 

这是我在开发时使用的,在没有存档时首先写入一个,然后再读取。这减小了编码量,保证主要流程清晰。

那么如何判断存档不存在呢?我之前想用标准c++的fstream函数,但是如果从CCUserDefalt中用getXMLFilePath获得存档路径的话。如果此时存档文件不存在,就会自动生成一个。所以接下来的判断存档是否存在代码就会失效了。

yanghuiliu的blog中提到了一个方法,我其实不建议使用这种缺省返回值的方式,但是cocos2dx就设计成这样了,所以可以使用这种方法。


  1. CCUserDefault *save=CCUserDefault::sharedUserDefault(); 
  2. if(save->getBoolForKey("isExisted")) 
  3.      //相关操作 
  4.      save->setBoolForKey("isExisted",true); 

参考文献:
cocos2d-x中保存用户游戏数据CCUserDefaulthttp://blog.csdn.net/yanghuiliu/article/details/6912612

 






 本文转自 老G 51CTO博客,原文链接:http://blog.51cto.com/goldlion/770754,如需转载请自行联系原作者