转载自:http://blog.segmentfault.com/codecabin/1190000000609378

在Cocos2d-x的学习和使用中,我遇到了很多关于数据的操作。在这个过程中,我学习了Cocos2d-x自带的很多功能。下面我把接触到的类罗列在下面,给出的都是基本的用法,多数没有深入了解。

UserDefault

UserDefault类就像一个小型的数据库,它可以被用来存储一些键值对。而且由于是单例模式,你可以在程序的任何地方使用这些数据。
头文件:

#include "base/CCUserDefault.h"

数据的存储:

UserDefault *ud = UserDefault::getInstance();// 从输入框中读取出字符串并加入到UserDefault中ud->setStringForKey("username", username->getStringValue());ud->setStringForKey("password", password->getStringValue());ud->flush();    // 将UserDefault中的内容写入到文件中

数据的读取:

// 将存储的数据读入到文本框,如果数据已经存储到本地,可以直接读username->setText(UserDefault::getInstance()->getStringForKey("username"));password->setText(UserDefault::getInstance()->getStringForKey("password"));

FileUtils

FileUtils类包括了对文件常用的操作,如获取路径、判断是否存在等,有点类似于Java中的File类,但除此之外,它还可以从文件中读内容。用的比较多还是读取文件内容到字符串:

#include "platform/CCFileUtils.h"if(FileUtils::getInstance()->isFileExist(filename))  {      std::string data=FileUtils::getInstance()->getStringFromFile(filename);  }  

更多FileUtils的用法可以看这篇文章。

rapidjson

从Cocos2d-x 3.0开始开始自带rapidjson这个类,解析json文件变得方便了。下面的示例从json中读取带有玩家名字和得分的排行榜信息。

#include "json/rapidjson.h"  #include "json/document.h"  rapidjson::Document doc;  // 创建一个解析JSON的Document对象doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());  // 假设数据存储在字符串data中for(int i=0;i<doc.Size();i++)  {       rapidjson::Value &v=doc[i];           std::string username;    int score;     if(v.HasMember("username") && v.HasMember("score"))      {           username = v["username"].GetString();  // 获取一个String属性        score = v["score"].GetInt();    // 获取一个int属性        texts[i]->setText(username + ": " + std::to_string(score);  // 将int转成String,加到一个文本框中    }  }  

NotificationCenter

同大多数学习者一样,我们一开始在层与层、场景与场景之间传递数据上面也很头疼,然后就在网上查到了这个类。他使用了观察者模式,只需要让一个类订阅另一个类的消息,就可以实现数据的传递。
在下面这个示例中,希望将CharacterLayer中的血量、生命数等传递到HUDLayer中显示。
CharacterLayer:

NotificationCenter::getInstance()->postNotification("loseHeroLife",NULL);   // 传递生命数减少的消息,没有传递额外的对象NotificationCenter::getInstance()->postNotification("getHealth",heroHealth);    // 传递此时的血量,heroHealth对象中存储了血量的信息

HUDLayer:

NotificationCenter::getInstance()->addObserver(this,callfuncO_selector(HUDLayer::loseHeroLife),"loseHeroLife",NULL);    // 在loseHeroLife中将显示的红心减一NotificationCenter::getInstance()->addObserver(this,callfuncO_selector(HUDLayer::getHealth),"getHealth",NULL);  // 从接收到的heroHealth更新血槽的显示

绑定的处理方法应该是这个样子的:

void HUDLayer::getHealth(Object* pSender){    heroHealth = (Health*)pSender;}

HttpClient

下面就是数据通过网络传输的内容了。HttpClient及相关类可以实现发送Http请求及接收响应。以用户注册的代码为例:

HttpRequest* request = new HttpRequest();  std::string url = LOGIN_SERVER_URL + username_s + "/" + password_s;request->setUrl(url.c_str());  request->setRequestType(HttpRequest::Type::GET);  // 还可以使用request->setRequestData("a", 0)的方式设置参数,这里没有用到  request->setResponseCallback(this, httpresponse_selector(LoginScene::onHttpRequestCompleted));    HttpClient::getInstance()->send(request);  request->release();

onHttpRequestCompleted是一个回调方法,用于处理Http响应。它长这个样子:

void LoginScene::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response) {      if(!response || !response->isSucceed())        return;    // 获取响应中的内容    std::vector<char>* buffer = response->getResponseData();      std::stringstream ss;    for(int i=0;i<buffer->size();i++){        ss << (*buffer)[i];    }    // 做相应处理    if(ss.str() == ”success“){        // 登录成功    }else{        // 登录失败    }}