cocos2d-x中保存用户游戏数据CCUserDefault

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

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

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

[cpp]  view plain copy
  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返回自己想要的值。

[cpp]  view plain copy
  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实在太长了。

[cpp]  view plain copy
  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方法去获取。 

[cpp]  view plain copy
  1. if ( !LoadBooleanFromXML("_IS_EXISTED"))   
  2.   
  3. {  
  4.   
  5.        initUserData();               
  6.   
  7.        SaveBooleanToXML("_IS_EXISTED"true);  
  8.   
  9. }  


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值