Cocos2d-x之数据的处理

|   版权声明:本文为博主原创文章,未经博主允许不得转载。

 

FileUtils

    在游戏中,用户要保存自己的偏好设置和玩家的信息,都需要涉及到游戏数据的处理。首先要想处理数据,则要找到文件,创建文件,读写文件...;在Cocos2d-x中有一个类FileUtils,FileUtils是Cocos2d-x引擎中封装的一个简单的文件操作类,该类几乎实现了所有文件操作的功能,类FileUtils并不只是一个文件,也不是两个文件。在每个平台都会有一个FileUtils的头文件和实现文件。在游戏的开始阶段,游戏的文件资源一般都是存放在硬盘中,在游戏开始的时候,文件操作模块就会将硬盘中的资源转移到内存中。

在游戏中文件的读取分为三个部分:

    1. 资源存放在硬盘中

    2. 资源存放在内存中

    3. 资源存放在缓存中

                 

 API常用函数介绍:

  1 /**  Gets the instance of FileUtils.获得文件模块的单例对象 */
  2 static FileUtils* getInstance();
  3 /**  Destroys the instance of FileUtils.释放文件模块*/
  4 static void destroyInstance(); 
  5 /**     清空缓存
  6 *  Purges full path caches.
  7 */
  8 virtual void purgeCachedEntries();
  9 /**     从文件中获取字符串。
 10 *  Gets string from a file.
 11 */
 12 virtual std::string getStringFromFile(const std::string& filename);
 13 /** 获得资源文件的内容
 14 *  Creates binary data from a file.
 15 *  @return A data object.
 16 */
 17 virtual Data getDataFromFile(const std::string& filename);
 18 /** 获取资源文件数据
 19 *  Gets resource file data
 20 *  @param[in]  filename The resource file name which contains the path.
 21 *  @param[in]  mode The read mode of the file.
 22 *  @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
 23 *  @return Upon success, a pointer to the data is returned, otherwise NULL.
 24 *  @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
 25 */
 26 CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size);
 27 /**     从zip文件中获得资源文件的内容
 28 *  Gets resource file data from a zip file.
 29 *  @param[in]  filename The resource file name which contains the relative path of the zip file.
 30 *  @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
 31 *  @return Upon success, a pointer to the data is returned, otherwise nullptr.
 32 *  @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
 33 */
 34 virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);
 35 /** 获得一个文件的绝对路径,返回值为文件的绝对路径(通过文件名查找文件,并将它所在的路径返回)
 36 *       Returns the fullpath for a given filename.
 37 */
 38 virtual std::string fullPathForFilename(const std::string &filename) const;
 39 /** 通过一个文件名在字典容器中查找文件
 40 * Loads the filenameLookup dictionary from the contents of a filename.
 41 * @note The plist file name should follow the format below:
 42 */
 43 virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
 44 /** 设置一个按文件名查找的字典。
 45 *  Sets the filenameLookup dictionary.
 46 *  @param pFilenameLookupDict The dictionary for replacing filename.
 47 */
 48 virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
 49 /**     获得一个文件的绝对路径包含文件名
 50 *  Gets full path from a file name and the path of the relative file.
 51 */
 52 virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
 53 /**     设置数组容器内所包含的资源的搜索顺序。
 54 *  Sets the array that contains the search order of the resources.
 55 *  @param searchResolutionsOrder The source array that contains the search order of the resources.
 56 *  @see getSearchResolutionsOrder(), fullPathForFilename(const char*).
 57 */
 58 virtual void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);
 59 /**     追加资源的搜索顺序。
 60 * Append search order of the resources.
 61 * @see setSearchResolutionsOrder(), fullPathForFilename().
 62 */
 63 virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false);
 64 /**     获取数组中所包含的资源的搜索顺序
 65 *  Gets the array that contains the search order of the resources.
 66 *  @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*).
 67 */
 68 virtual const std::vector<std::string>& getSearchResolutionsOrder() const;
 69 /**     设置资源路径
 70 *  Sets the array of search paths.
 71 */
 72 virtual void setSearchPaths(const std::vector<std::string>& searchPaths);
 73 /**     设置默认资源的根路径。
 74 * Set default resource root path.
 75 */
 76 void setDefaultResourceRootPath(const std::string& path);
 77 /**     添加搜索路径。
 78 * Add search path.
 79 */
 80 void addSearchPath(const std::string & path, const bool front=false);
 81 /** 获取的搜索路径的数组。
 82 *  Gets the array of search paths.
 83 */
 84 virtual const std::vector<std::string>& getSearchPaths() const;
 85 /**     获取可写的路径。
 86 *  Gets the writable path.
 87 *  @return  The path that can be write/read a file in
 88 */
 89 virtual std::string getWritablePath() const = 0;
 90 /**     设置可写的路径。
 91 *  Sets writable path.
 92 */
 93 virtual void setWritablePath(const std::string& writablePath);
 94 /**     设置在无法加载图像时候是否弹出一个消息框。
 95 *  Sets whether to pop-up a message box when failed to load an image.
 96 */
 97 virtual void setPopupNotify(bool notify);
 98 /** 检查在无法加载图像的时候是否弹出一个消息框。
 99 *       Checks whether to pop up a message box when failed to load an image.
100 *  @return True if pop up a message box when failed to load an image, false if not.
101 */
102 virtual bool isPopupNotify() const;
103 /**     文件到ValueMap的内容转换。(将文件中的内容转换成ValueMap类型)
104 *  Converts the contents of a file to a ValueMap.
105 *  @param filename The filename of the file to gets content.
106 *  @return ValueMap of the file contents.
107 *  @note This method is used internally.
108 */
109 virtual ValueMap getValueMapFromFile(const std::string& filename);
110 /** Converts the contents of a file to a ValueMap.
111 *  This method is used internally.
112 */
113 virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
114 /**     写一个内容为ValueMap类型的plist文件
115 * write a ValueMap into a plist file
116 *@param dict the ValueMap want to save
117 *@param fullPath The full path to the file you want to save a string
118 *@return bool
119 */
120 virtual bool writeToFile(ValueMap& dict, const std::string& fullPath);
121 /** 写一个内容为String类型的.plist文件
122 *  write a string into a file
123 * @param dataStr the string want to save
124 * @param fullPath The full path to the file you want to save a string
125 * @return bool True if write success
126 */
127 virtual bool writeStringToFile(std::string dataStr, const std::string& fullPath);
128 /**
129 * write Data into a file
130 *@param retData the data want to save
131 *@param fullPath The full path to the file you want to save a string
132 *@return bool
133 */
134 virtual bool writeDataToFile(Data retData, const std::string& fullPath);
135 /**
136 * write ValueMap into a plist file
137 *@param dict the ValueMap want to save
138 *@param fullPath The full path to the file you want to save a string
139 *@return bool
140 */
141 virtual bool writeValueMapToFile(ValueMap& dict, const std::string& fullPath);
142 /**
143 * write ValueVector into a plist file
144 *@param vecData the ValueVector want to save
145 *@param fullPath The full path to the file you want to save a string
146 *@return bool
147 */
148 virtual bool writeValueVectorToFile(ValueVector vecData, const std::string& fullPath);
149 /**
150 * Windows fopen can't support UTF-8 filename
151 * Need convert all parameters fopen and other 3rd-party libs
152 * @param filename std::string name file for conversion from utf-8
153 * @return std::string ansi filename in current locale
154 */
155 virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const;
156 // Converts the contents of a file to a ValueVector.
157 // This method is used internally.
158 virtual ValueVector getValueVectorFromFile(const std::string& filename);
159 /**     判断文件是否存在
160 *  Checks whether a file exists.
161 *  @note If a relative path was passed in, it will be inserted a default root path at the beginning.
162 *  @param filename The path of the file, it could be a relative or absolute path.
163 *  @return True if the file exists, false if not.
164 */
165 virtual bool isFileExist(const std::string& filename) const;
166 /** 获取文件的扩展名是在较低的情况下的后缀(由点从基本文件名隔开)。
167 *  Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.
168 *  Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.
169 *  @param filePath The path of the file, it could be a relative or absolute path.
170 *  @return suffix for filename in lower case or empty if a dot not found.
171 */
172 virtual std::string getFileExtension(const std::string& filePath) const;
173 /**     检查路径是否是绝对路径。
174 *  Checks whether the path is an absolute path.t.
175 */
176 virtual bool isAbsolutePath(const std::string& path) const;
177 /**检查路径是否是一个目录。
178 *  Checks whether the path is a directory.
179 *  @param dirPath The path of the directory, it could be a relative or an absolute path.
180 *  @return True if the directory exists, false if not.
181 */
182 virtual bool isDirectoryExist(const std::string& dirPath) const;
183 /**     创建一个字典目录
184 *  Creates a directory.
185 *  @param dirPath The path of the directory, it must be an absolute path.
186 *  @return True if the directory have been created successfully, false if not.
187 */
188 virtual bool createDirectory(const std::string& dirPath);
189 /**     移除一个目录
190 *  Removes a directory.
191 *  @param dirPath  The full path of the directory, it must be an absolute path.
192 *  @return True if the directory have been removed successfully, false if not.
193 */
194 virtual bool removeDirectory(const std::string& dirPath);
195 /**     移除一个文件
196 *  Removes a file.
197 *  @param filepath The full path of the file, it must be an absolute path.
198 *  @return True if the file have been removed successfully, false if not.
199 */
200 virtual bool removeFile(const std::string &filepath);
201 /**     给指定目录下的文件重命名
202 *  Renames a file under the given directory.
203 *  @param path     The parent directory path of the file, it must be an absolute path.
204 *  @param oldname  The current name of the file.
205 *  @param name     The new name of the file.
206 *  @return True if the file have been renamed successfully, false if not.
207 */
208 virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name);
209 /** 给指定目录下的文件重命名
210 *  Renames a file under the given directory.
211 *  @param oldfullpath  The current fullpath of the file. Includes path and name.
212 *  @param newfullpath  The new fullpath of the file. Includes path and name.
213 *  @return True if the file have been renamed successfully, false if not.
214 */
215 
216 virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath);
217 /**     检索文件的大小
218 *  Retrieve the file size.
219 *  @note If a relative path was passed in, it will be inserted a default root path at the beginning.
220 *  @param filepath The path of the file, it could be a relative or absolute path.
221 *  @return The file size.
222 */
223 virtual long getFileSize(const std::string &filepath);
224 /** 返回的完整路径缓存。
225 *       Returns the full path cache.
226 */
227 const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }
228 
229 protected CONUT:
230 
231 /** 在字典中使用一个文件的密钥来查找文件名
232 *       Dictionary used to lookup filenames based on a key.
233 *  It is used internally by the following methods:基于下面的方法在内部使用
234 *  std::string fullPathForFilename(const char*);
235 */
236 ValueMap _filenameLookupDict;
237 /** 该Vector容器包含有分辨率文件夹。元素在此向量的低指数,该决议目录优先级越高。
238 *  The vector contains resolution folders.
239 *  The lower index of the element in this vector, the higher priority for this resolution directory.
240  */
241 std::vector<std::string> _searchResolutionsOrderArray;
242 /**Vector容器包含的搜索路径。
243 * The vector contains search paths.
244 * The lower index of the element in this vector, the higher priority for this search path.
245 */
246 std::vector<std::string> _searchPathArray;
247 /**     资源的默认根路径。
248 *  The default root path of resources.
249 *  If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass.
250 *  For instance:
251 *  On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init().
252 *  Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
253 */
254 std::string _defaultResRootPath;
255 /**     完整路径缓存。当一个文件被发现,它将被添加到该高速缓存。
256 *  The full path cache. When a file is found, it will be added into this cache.
257 *  This variable is used for improving the performance of file search.
258 */
259 mutable std::unordered_map<std::string, std::string> _fullPathCache;
260 /**可写路径。
261 * Writable path.
262 */
263 std::string _writablePath;
264 /**     文件实用的单指针。
265 *  The singleton pointer of FileUtils.
266 */
267 static FileUtils* s_sharedFileUtils;
View Code

 

实例:

.h files

#ifndef _FILEUTILSTEST_SCENE_H_
#define _FILEUTILSTEST_SCENE_H_
#include "cocos2d.h"
class fileUtil : public cocos2d::Layer
{
private:
public:
        static cocos2d::Scene* createScene();
        virtual bool init();
        void fileUtil::testResolutionDirectories(Ref* sender);
        void fileUtil::testSearchPath(Ref* sender);
        void fileUtil::testFilenameLookup(Ref* sender);
        void fileUtil::testIsFileExist(Ref* sender);
        void fileUtil::testWritePlist(Ref* sender);
        CREATE_FUNC(fileUtil);
};
#endif // _FILEUTILSTEST_SCENE_H_



.cpp files

#include "fileUtilsTest.h"

USING_NS_CC;

Scene* fileUtil::createScene()
{
        auto scene = Scene::create();
        auto layer = fileUtil::create();
        scene->addChild(layer);
        return scene;
}

bool fileUtil::init()
{
        if (!Layer::init())
        {
               return false;
        }

        Size visibleSize = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();

        auto item1 = MenuItemFont::create("testResolutionDirectories", CC_CALLBACK_1(fileUtil::testResolutionDirectories, this));
        auto item2 = MenuItemFont::create("testSearchPath", CC_CALLBACK_1(fileUtil::testSearchPath, this));
        auto item3 = MenuItemFont::create("testFilenameLookup", CC_CALLBACK_1(fileUtil::testFilenameLookup, this));
        auto item4 = MenuItemFont::create("testIsFileExist", CC_CALLBACK_1(fileUtil::testIsFileExist, this));
        auto item5 = MenuItemFont::create("testWritePlist", CC_CALLBACK_1(fileUtil::testWritePlist, this));

        auto menu = Menu::create(item1, item2, item3, item4, item5, NULL);
        menu->setPosition(Vec2(250, visibleSize.height - 200));
        menu->alignItemsVerticallyWithPadding(20);
        this->addChild(menu);

        return true;
}

//设置和获得分辨率的路径;获取某个文件的路径
void fileUtil::testResolutionDirectories(Ref* sender)
{
//不同的平台的不同的设备它们的分辨率也存在着某些差异
        //实例化
        auto fileUtil = FileUtils::getInstance();
        //清除缓存,清空所有的缓存
        fileUtil->purgeCachedEntries();
        
        //默认搜索路径,第一次的默认搜索路径是Resource那个文件夹
        std::vector<std::string> _defaultSearchPathArray;
        _defaultSearchPathArray = fileUtil->getSearchPaths();
        std::vector<std::string> searchPath = _defaultSearchPathArray;
        
        //在默认的搜索路径下在添加一个我们自己的搜索路径
        searchPath.insert(searchPath.begin(), "Misc");
        //设置新的搜索路径为"Misc"
        fileUtil->setSearchPaths(searchPath);

        //获得搜索分辨率资源路径
        std::vector<std::string> _defaultResolutionsOrderArray = fileUtil->getSearchResolutionsOrder();
        std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray;

        //添加分辨率资源路径
        //在依次的在下面的文件名路径下依次的查找所要查找的内容
        resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd");
        resolutionsOrder.insert(resolutionsOrder.begin() + 1, "resources-ipad");
        resolutionsOrder.insert(resolutionsOrder.begin() + 2, "resources-widehd");
        resolutionsOrder.insert(resolutionsOrder.begin() + 3, "resources-wide");
        resolutionsOrder.insert(resolutionsOrder.begin() + 4, "resources-hd");
        resolutionsOrder.insert(resolutionsOrder.begin() + 5, "resources-iphone");

        //重新设置路径
        fileUtil->setSearchResolutionsOrder(resolutionsOrder);

        for (int i = 1; i < 7; i++)
        {
               //创建6个文件名:text~.txt
               auto filename = String::createWithFormat("test%d.txt", i);
               //fullPathForFilename(filename->getCString())取得当前对象文件的一个绝对路径;如何查找,它会在上面所有设定好的文件名称下,依次的来查找
               std::string ret = fileUtil->fullPathForFilename(filename->getCString());
               log("%s --> %s", filename->getCString(), ret.c_str());
        }
}

//搜索路径
void fileUtil::testSearchPath(Ref* sender)
{
//实例化
        auto fileUtil = FileUtils::getInstance();
        std::string ret;
        //清除缓存,清空所有的缓存
        fileUtil->purgeCachedEntries();
        std::vector<std::string> _defaultSearchPathArray = fileUtil->getSearchPaths();
        std::vector<std::string> searchPaths = _defaultSearchPathArray;
        //getWritablePath();获得一个可写的路径
        std::string writablePath = fileUtil->getWritablePath();

        std::string fileName = writablePath + "external.txt";
        char szBuf[100] = "Hello Cocos2d-x!";
        FILE* fp = fopen(fileName.c_str(), "wb");
        if (fp)
        {
               size_t ret = fwrite(szBuf, 1, strlen(szBuf), fp);
               CCASSERT(ret != 0, "fwrite function returned zero value");
               fclose(fp);
               if (ret != 0)
                       log("Writing file to writable path succeed");
        }
//下面是设置或者添加几个可写分辨路径
        searchPaths.insert(searchPaths.begin(), writablePath);
        searchPaths.insert(searchPaths.begin() + 1, "Misc/searchpath1");
        searchPaths.insert(searchPaths.begin() + 2, "Misc/searchpath2");
        fileUtil->setSearchPaths(searchPaths);
//取得分辨路径
        std::vector<std::string> _defaultResolutionsOrderArray = fileUtil->getSearchResolutionsOrder();
        std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray;
//添加一个路径resources-ipad
        resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad");
        fileUtil->setSearchResolutionsOrder(resolutionsOrder);

        for (int i = 1; i<3; i++)
        {
               auto filename = String::createWithFormat("file%d.txt", i);
               ret = fileUtil->fullPathForFilename(filename->getCString());
               log("%s --> %s", filename->getCString(), ret.c_str());
        }

        // Gets external.txt from writable path
        std::string fullPath = fileUtil->fullPathForFilename("external.txt");
        log("external file path = %s", fullPath.c_str());
        if (fullPath.length()>0)
        {//rb是一个只读的权限
               fp = fopen(fullPath.c_str(), "rb");
               if (fp)
               {
                       char szReadBuf[100] = { 0 };
                       int read = fread(szReadBuf, 1, strlen(szBuf), fp);
                       if (read>0)
                       {
                               log("The content of file from writable path: %s", szReadBuf);
                       }
                       fclose(fp);
               }
        }
}

//文件查找
//测试文件名查找
void fileUtil::testFilenameLookup(Ref* sender)
{
//实例化
        auto sharedFileUtils = FileUtils::getInstance();
        ValueMap dict;
        dict["grossini.bmp"] = Value("Images/grossini.png");
        dict["grossini.xcf"] = Value("Images/grossini.png");
//设置一个按文件名查找的字典
        sharedFileUtils->setFilenameLookupDictionary(dict);

        // Instead of loading carlitos.xcf, it will load grossini.png
        auto sprite = Sprite::create("grossini.png");
        this->addChild(sprite);

        auto s = Director::getInstance()->getWinSize();
        sprite->setPosition(Vec2(s.width / 2, s.height / 2));
}

//判断文件是否存在
//测试文件是否存在
void fileUtil::testIsFileExist(Ref* sender)
{
        auto s = Director::getInstance()->getWinSize();
        auto sharedFileUtils = FileUtils::getInstance();

        Label* pTTF = nullptr;
        bool isExist = false;

        isExist = sharedFileUtils->isFileExist("Images/grossini.png");

        pTTF = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20);
        pTTF->setPosition(Vec2(s.width / 2, s.height / 3));
        this->addChild(pTTF);
}

//写plist配置文件
//测试写plist文件
void fileUtil::testWritePlist(Ref* sender)
{
//创建一个字典
        auto root = Dictionary::create();
//设置字典的key-》String element value
        auto string = String::create("String element value");
        root->setObject(string, "string element key");
//创建一个数组
        auto array = Array::create();
//在数组里面添加一个字典
        auto dictInArray = Dictionary::create();
//往字典里面添加两个对象
        dictInArray->setObject(String::create("string in dictInArray value 0"), "string in dictInArray key 0");
        dictInArray->setObject(String::create("string in dictInArray value 1"), "string in dictInArray key 1");
//再将字典添加到数组里面去
        array->addObject(dictInArray);

        array->addObject(String::create("string in array"));
//在数组中在添加一个数组
        auto arrayInArray = Array::create();
        arrayInArray->addObject(String::create("string 0 in array"));
        arrayInArray->addObject(String::create("string 1 in array"));
        array->addObject(arrayInArray);
        
        root->setObject(array,"array");
//在字典中在嵌套字典   
        auto dictInDict = Dictionary::create();
        dictInDict->setObject(String::create("string in dictInDict value"), "String in dictInDict key");

        //add booleans to the plist
        auto booleanObject = Bool::create(true);
        dictInDict->setObject(booleanObject, "bool");

        //add integer to the plist
        auto intObject = Integer::create(624);
        dictInDict->setObject(intObject, "integer");

        //add float to the plist
        auto floatObject = Float::create(524.2);
        dictInDict->setObject(floatObject, "float");

        //add double to the plist
        auto doubleObject = Double::create(524.2);
        dictInDict->setObject(doubleObject, "double");
        root->setObject(dictInDict, "dictInDict, hello world!");

        //end with
        //在拿到一个可写的路径getWritablePath();-——》writablePath
        std::string writablePath = FileUtils::getInstance()->getWritablePath();
        //在拿到的可写路径下添加一个text.plist文件
        std::string fullPath = writablePath + "text.plist";
        //调用writeToFile方法进行写操作
        if (root->writeToFile(fullPath.c_str()))
               log("see the plist file at %s", fullPath.c_str());
        else
               log("write plist file failed");

        auto label = LabelTTF::create(fullPath.c_str(), "Arial", 12);
        this->addChild(label);
        auto winsize = Director::getInstance()->getWinSize();
        label->setPosition(Vec2(winsize.width / 2, winsize.height / 3));
//根据文件的内容来创建一个字典
        auto loadDict = __Dictionary::createWithContentsOfFile(fullPath.c_str());
        auto loadDictInDict = (__Dictionary*)loadDict->objectForKey("dictInDict,hello world");
        auto boolValue = (__String*)loadDictInDict->objectForKey("bool");
        CCLOG("%s", boolValue->getCString());
        auto floatValue = (__String*)loadDictInDict->objectForKey("float");
        CCLOG("%s", floatValue->getCString());
        auto doubleValue = (__String*)loadDictInDict->objectForKey("double");
        CCLOG("%s", doubleValue->getCString());
        auto integerValue = (__String*)loadDictInDict->objectForKey("int");
        CCLOG("%s", integerValue->getCString());
}

 

 

 

UserDefault

    在上面实现了数据的读写等一些操作,但是游戏的某些数据时要实现持久化的,因此Cocos2d-x引擎中有提供了一个类UserDefault来让我们来实现数据的持久化。UserDefault可以实现数据的存储,但是它不宜储存大量的数据,一般的情况下,用于保存一些游戏设置和玩家偏好设置;数据持久化就是数据能够存储起来,然后在需要的时候可以查找回来,即使设备从新启动也可以查找回来。在UserDefault提供了对int, double, bool和string等数据类型的读写。

UserDefault所支持的数据类型:

在Cocos2d-x中能够多种持久化的方式;

1. 普通文本文件的持久化。

2. UserDefault.可以设置用户的偏好设置等一些少量的数据

3. 属性列表。

4. SQL数据库

 

API中的常用函数:

  1 // get value methods
  2 /**根据键值取出布尔值
  3 * Get bool value by key, if the key doesn't exist, will return false.
  4 * You can set the default value, or it is false.
  5 * @param key The key to get value.
  6 * @return Bool value by `key`.
  7 */
  8 bool getBoolForKey(const char* key);    
  9 /**根据键值取出布尔值,如果键不存在,返回defaultValue
 10 * Get bool value by key, if the key doesn't exist, will return passed default value.
 11 * @param key The key to get value.
 12 * @param defaultValue The default value to return if the key doesn't exist.
 13 */
 14 virtual bool getBoolForKey(const char* key, bool defaultValue);    
 15 /**根据键值取出int类型的数据
 16 * Get integer value by key, if the key doesn't exist, will return 0.
 17 * You can set the default value, or it is 0.
 18 * @param key The key to get value.
 19 * @return Integer value of the key.
 20 */
 21 int getIntegerForKey(const char* key);    
 22 /**根据键值取出int类型的数据,如果键不存在,返回defaultValue
 23 * Get bool value by key, if the key doesn't exist, will return passed default value.
 24 * @param key The key to get value.
 25 * @param defaultValue The default value to return if the key doesn't exist.
 26 * @return Integer value of the key.
 27 */
 28 virtual int getIntegerForKey(const char* key, int defaultValue);    
 29 /**根据键值取出float类型的数据
 30 * Get float value by key, if the key doesn't exist, will return 0.0.
 31 * @param key The key to get value.
 32 * @return Float value of the key.
 33 */
 34 float getFloatForKey(const char* key);    
 35 /**根据键值取出float类型的数据,如果键不存在,返回defaultValue
 36 * Get float value by key, if the key doesn't exist, will return passed default value.
 37 * @param key The key to get value.
 38 * @param defaultValue The default value to return if the key doesn't exist.
 39 * @return Float value of the key.
 40 */
 41 virtual float getFloatForKey(const char* key, float defaultValue);    
 42 /**根据键值取出double类型的数据
 43 * Get double value by key, if the key doesn't exist, will return 0.0.
 44 * @param key The key to get value.
 45 * @return Double value of the key.
 46 */
 47 double getDoubleForKey(const char* key);    
 48 /**根据键值取出double类型的数据,如果键不存在,返回defaultValue
 49 * Get double value by key, if the key doesn't exist, will return passed default value.
 50 * @param key The key to get value.
 51 * @param defaultValue The default value to return if the key doesn't exist.
 52 * @return Double value of the key.
 53 */
 54 virtual double getDoubleForKey(const char* key, double defaultValue);    
 55 /**根据键值取出string类型的数据
 56 * Get string value by key, if the key doesn't exist, will return an empty string.
 57 * @param key The key to get value.
 58 * @return String value of the key.
 59 */
 60 std::string getStringForKey(const char* key);    
 61 /**根据键值取出string类型的数据,如果键不存在,返回defaultValue
 62 * Get string value by key, if the key doesn't exist, will return passed default value.
 63 * @param key The key to get value.
 64 * @param defaultValue The default value to return if the key doesn't exist.
 65 * @return String value of the key.
 66 */
 67 virtual std::string getStringForKey(const char* key, const std::string & defaultValue);    
 68 /**根据键值取出Data类型的数据
 69 * Get Data value by key, if the key doesn't exist, will return an empty Data.
 70 * @param key The key to get value.
 71 * @return Data value of the key.
 72 */
 73 Data getDataForKey(const char* key);    
 74 /**根据键值取出Data类型的数据,如果键不存在,返回defaultValue
 75 * Get Data value by key, if the key doesn't exist, will return an empty Data.
 76 * @param key The key to get value.
 77 * @param defaultValue The default value to return if the key doesn't exist.
 78 * @return Data value of the key.
 79 */
 80 virtual Data getDataForKey(const char* key, const Data& defaultValue);
 81 // set value methods
 82 /**根据键写入布尔值
 83 * Set bool value by key.
 84 * @param key The key to set.
 85 * @param value A bool value to set to the key.
 86 */
 87 virtual void setBoolForKey(const char* key, bool value);
 88 /**根据键写入int类型数据
 89 * Set integer value by key.
 90 * @param key The key to set.
 91 * @param value A integer value to set to the key.
 92 */
 93 virtual void setIntegerForKey(const char* key, int value);
 94 /**根据键写入float类型数据
 95 * Set float value by key.
 96 * @param key The key to set.
 97 * @param value A float value to set to the key.
 98 */
 99 virtual void setFloatForKey(const char* key, float value);
100 /**根据键写入double类型数据
101 * Set double value by key.
102 * @param key The key to set.
103 * @param value A double value to set to the key.
104 */
105 virtual void setDoubleForKey(const char* key, double value); 
106 /**根据键写入String类型数据
107 * Set string value by key.
108 * @param key The key to set.
109 * @param value A string value to set to the key.
110 */
111 virtual void setStringForKey(const char* key, const std::string & value);   
112 /**根据键写入Data类型数据
113 * Set Data value by key.
114 * @param key The key to set.
115 * @param value A Data value to set to the key.
116 */
117 virtual void setDataForKey(const char* key, const Data& value);      
118 /**调用此函数会将我们所改变的数据保存在.xml文件中去。
119 * You should invoke this function to save values set by setXXXForKey().
120 */
121 virtual void flush();
122 /**
123 * delete any value by key,
124 * @param key The key to delete value.
125 */
126 virtual void deleteValueForKey(const char* key);    
127 /** 
128 * Returns the singleton.
129 */
130 static UserDefault* getInstance();    
131 /**
132 * 
133 */
134 static void destroyInstance();
135 /**
136 * You can inherit from platform dependent implementation of UserDefault, such as UserDefaultAndroid,
137 * and use this function to set delegate, then UserDefault will invoke delegate's implementation.
138 * For example, your store native data base or other format store.
139 * If you don't want to system default implementation after setting delegate, you can just pass nullptr
140 * to this function.
141 * @warm It will delete previous delegate
142 */
143 static void setDelegate(UserDefault *delegate);
144 /** @deprecated Use getInstace() instead.
145 */
146 CC_DEPRECATED_ATTRIBUTE static UserDefault* sharedUserDefault();
147 /**@deprecated Use destroyInstance() instead.
148 */
149 CC_DEPRECATED_ATTRIBUTE static void purgeSharedUserDefault();
150 /** All supported platforms other iOS & Android use xml file to save values. This function is return the file path of the xml path.
151 */
152 static const std::string& getXMLFilePath();
153 /** All supported platforms other iOS & Android and CC_PLATFORM_WINRT use xml file to save values. This function checks whether the xml file exists or not.
154 * @return True if the xml file exists, false if not.
155 */
156 static bool isXMLFileExist();
View Code

 

实例:

.h files 

#ifndef _USERDEFAULTTEST_SCENE_H_
#define _USERDEFAULTTEST_SCENE_H_
#include "cocos2d.h"
class userDefault : public cocos2d::Layer
{
private:
public:
        static cocos2d::Scene* createScene();
        virtual bool init();
        void testUserDefault(Ref* sendef);
        CREATE_FUNC(userDefault);
};

#endif // _USERDEFAULTTEST_SCENE_H_

.cpp files

#include "UserDefaultTest.h"

USING_NS_CC;

Scene* userDefault::createScene()
{
        auto scene = Scene::create();
        auto layer = userDefault::create();
        scene->addChild(layer);
        return scene;
}

bool userDefault::init()
{
        if (!Layer::init())
        {
               return false;
        }

        Size visibleSize = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();

        auto item = MenuItemFont::create("Test", CC_CALLBACK_1(userDefault::testUserDefault, this));
        auto menu = Menu::create(item, NULL);
        this->addChild(menu);

        return true;
}

void userDefault::testUserDefault(Ref* sendef)
{
        //set default value
        UserDefault::getInstance()->setStringForKey("String", "value1");
        UserDefault::getInstance()->setIntegerForKey("Integer", 100);
        UserDefault::getInstance()->setFloatForKey("Float", 5.326f);
        UserDefault::getInstance()->setDoubleForKey("Double", 3.1415967);
        UserDefault::getInstance()->setBoolForKey("Bool", false);

        //printf value
        std::string ret = UserDefault::getInstance()->getStringForKey("String");
        CCLOG("string is %s", ret.c_str());

        int intValue = UserDefault::getInstance()->getIntegerForKey("Integer");
        CCLOG("Integer value is %d", intValue);

        float floValue = UserDefault::getInstance()->getFloatForKey("Float");
        CCLOG("Float value is %f", floValue);

        double douValue = UserDefault::getInstance()->getDoubleForKey("Double");
        CCLOG("Double value is %f", douValue);

        bool boolValue = UserDefault::getInstance()->getBoolForKey("Bool");
        if (boolValue)
               CCLOG("bool value is true");
        else
               CCLOG("bool value is false");


        //CCUserDefault::getInstance()->flush();
        CCLOG("改变后的数据:");
        UserDefault::getInstance()->setStringForKey("String", "value2");
        UserDefault::getInstance()->setIntegerForKey("Integer", 10);
        UserDefault::getInstance()->setFloatForKey("Float", 15.326f);
        UserDefault::getInstance()->setDoubleForKey("Double", 2 * 3.1415967);
        UserDefault::getInstance()->setBoolForKey("Bool", true);

        UserDefault::getInstance()->flush();

        //after change value
        ret = UserDefault::getInstance()->getStringForKey("String");
        CCLOG("string is %s", ret.c_str());

        intValue = UserDefault::getInstance()->getIntegerForKey("Integer");
        CCLOG("Integer value is %d", intValue);

        floValue = UserDefault::getInstance()->getFloatForKey("Float");
        CCLOG("Float value is %f", floValue);

        douValue = UserDefault::getInstance()->getDoubleForKey("Double");
        CCLOG("Double value is %f", douValue);

        boolValue = UserDefault::getInstance()->getBoolForKey("Bool");
        if (boolValue)
               CCLOG("bool value is true");
        else
               CCLOG("bool value is false");
}

posted @ 2016-08-23 15:31  Geore  阅读(735)  评论(0编辑  收藏  举报