打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
CCUserDefault

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

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

  1. void    setBoolForKey(const char* pKey, bool value);  
  2. void    setIntegerForKey(const char* pKey, int value);  
  3. void    setFloatForKey(const char* pKey, float value);  
  4. void    setDoubleForKey(const char* pKey, double value);  
  5. void    setStringForKey(const char* pKey, const std::string & value);  


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

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


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

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

 

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

  1. #define SaveStringToXML CCUserDefault::sharedUserDefault()->setStringForKey  
  2.   
  3. #define SaveIntegerToXML CCUserDefault::sharedUserDefault()->setIntegerForKey  
  4.   
  5. #define SaveBooleanToXML CCUserDefault::sharedUserDefault()->setBoolForKey  
  6.   
  7. #define LoadStringFromXML CCUserDefault::sharedUserDefault()->getStringForKey  
  8.   
  9. #define LoadIntegerFromXML CCUserDefault::sharedUserDefault()->getIntegerForKey  
  10.   
  11. #define LoadBooleanFromXML CCUserDefault::sharedUserDefault()->getBoolForKey  


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

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

  1. if ( !LoadBooleanFromXML("_IS_EXISTED"))   
  2.   
  3. {  
  4.   
  5.        initUserData();               
  6.   
  7.        SaveBooleanToXML("_IS_EXISTED"true);  
  8.   
  9. }  


对了,ccUserDefault在0.9.1版本会在安卓平台下crash掉,更新源代码就OK了 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
INI文件的读取(C语言:GetPrivateProfileString/GetPrivateProfileInt)
Cocos2d-x的相关面试题
【COCOS2DX(2.X)_LUA开发之三】在LUA中使用自定义精灵(LUA脚本与自创建类之间的访问)及LUA基础讲解
【玩转cocos2d-x之二十八】cocos2d-x的消息和数据传递
tolua++ 使用有感
C 中的XML配置文件编程经验
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服