Today finally need to save data, we all know that COCOS2DX is the C + + version of OC, so also implemented the Userdefault, you can use it to save the game data.
This singleton class implements localized storage of basic data types, writing data into an XML file, reading a hash table through an XML file, and then using the key to fetch the value ~
Userdefault's getter and setter are easy to use and are not burdensome.
Go to the Chase:
The game uses an array that needs to be saved and read from the local each time it is opened. But Userdefault only supports the storage of the underlying data type (there is a setdataforkey, search, only know is to save the binary value, no one used), can only directly write the ~
The first thought of value is that the class can transform the underlying data type, for example: value ("123"). Asint () can get 123, so the array is rewritten as valuevector (the vector that holds the Value).
datacenter.h
#include "cocos2d.h"USING_NS_CC;class DataCenter{public: static DataCenter *getInstance(); void setValueVectorForKey(ValueVector &vector, const char *key); ValueVector getValueVectorByKey(const char *key);private: static DataCenter *_dataCenter;};
"DataCenter.cpp"
#include "DataCenter.h" #include "string.h" #define Splite ' | DataCenter * DataCenter:: _datacenter = nullptr; datacenter* datacenter::getinstance () {if (! _datacenter) {_datacenter = new DataCenter (); } return _datacenter; } void Datacenter::setvaluevectorforkey (Valuevector &vector, const char *key) {std::string valuestring = ""; for (int i = 0; i < vector.size (); i++) {valuestring = valuestring + vector.at (i). asstring (); if (i! = Vector.size ()-1) {valuestring + = Splite; }} userdefault::getinstance (), Setstringforkey (key, valuestring); } valuevector Datacenter::getvaluevectorbykey (const char * key) {Valuevector valuevector; std::string valuestring = Userdefault::getinstance (), Getstringforkey (key); Std::string::iterator i; std::string tmp = ""; for (i = Valuestring.begin(); I <= valuestring.end (); ++i) {if (const char) *i! = Splite && I! = Valuestring.end ()) {tmp + = *i; } else {Valuevector.push_back (Value (TMP)); TMP = ""; }} return valuevector; }
Implementation method:
- Write, iterate over an array, put it into a string and save it with Userdefault.
- Read, read the string by Userdefault, divide the string into an array
The use of the method is very simple, do not write test ...
Welcome to my blog:helkyle.tk
"Cocos2d-x" Userdefault Save Array (valuevector)