167+203x133x25 ub 355jr10+90

Cocos2d-x之数据的处理
时间: 16:55:33
&&&& 阅读:527
&&&& 评论:
&&&& 收藏:0
标签:|&& 版权声明:本文为博主原创文章,未经博主允许不得转载。
& & 在游戏中,用户要保存自己的偏好设置和玩家的信息,都需要涉及到游戏数据的处理。首先要想处理数据,则要找到文件,创建文件,读写文件...;在Cocos2d-x中有一个类FileUtils,FileUtils是Cocos2d-x引擎中封装的一个简单的文件操作类,该类几乎实现了所有文件操作的功能,类FileUtils并不只是一个文件,也不是两个文件。在每个平台都会有一个FileUtils的头文件和实现文件。在游戏的开始阶段,游戏的文件资源一般都是存放在硬盘中,在游戏开始的时候,文件操作模块就会将硬盘中的资源转移到内存中。
在游戏中文件的读取分为三个部分:
&&& 1. 资源存放在硬盘中
&&& 2. 资源存放在内存中
&&& 3. 资源存放在缓存中
& & & & & & & & &
&API常用函数介绍:
Gets the instance of FileUtils.获得文件模块的单例对象 */
2 static FileUtils* getInstance();
Destroys the instance of FileUtils.释放文件模块*/
4 static void destroyInstance();
Purges full path caches.
8 virtual void purgeCachedEntries();
从文件中获取字符串。
Gets string from a file.
12 virtual std::string getStringFromFile(const std::string& filename);
13 /** 获得资源文件的内容
Creates binary data from a file.
@return A data object.
17 virtual Data getDataFromFile(const std::string& filename);
18 /** 获取资源文件数据
Gets resource file data
@param[in]
filename The resource file name which contains the path.
@param[in]
mode The read mode of the file.
@param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
@return Upon success, a pointer to the data is returned, otherwise NULL.
@warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
26 CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size);
从zip文件中获得资源文件的内容
Gets resource file data from a zip file.
@param[in]
filename The resource file name which contains the relative path of the zip file.
@param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
@return Upon success, a pointer to the data is returned, otherwise nullptr.
@warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
34 virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);
35 /** 获得一个文件的绝对路径,返回值为文件的绝对路径(通过文件名查找文件,并将它所在的路径返回)
Returns the fullpath for a given filename.
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:
43 virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
44 /** 设置一个按文件名查找的字典。
Sets the filenameLookup dictionary.
@param pFilenameLookupDict The dictionary for replacing filename.
48 virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
获得一个文件的绝对路径包含文件名
Gets full path from a file name and the path of the relative file.
52 virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
设置数组容器内所包含的资源的搜索顺序。
Sets the array that contains the search order of the resources.
@param searchResolutionsOrder The source array that contains the search order of the resources.
@see getSearchResolutionsOrder(), fullPathForFilename(const char*).
58 virtual void setSearchResolutionsOrder(const std::vector&std::string&& searchResolutionsOrder);
追加资源的搜索顺序。
60 * Append search order of the resources.
61 * @see setSearchResolutionsOrder(), fullPathForFilename().
63 virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false);
获取数组中所包含的资源的搜索顺序
Gets the array that contains the search order of the resources.
@see setSearchResolutionsOrder(const std::vector&std::string&&), fullPathForFilename(const char*).
68 virtual const std::vector&std::string&& getSearchResolutionsOrder() const;
设置资源路径
Sets the array of search paths.
72 virtual void setSearchPaths(const std::vector&std::string&& searchPaths);
设置默认资源的根路径。
74 * Set default resource root path.
76 void setDefaultResourceRootPath(const std::string& path);
添加搜索路径。
78 * Add search path.
80 void addSearchPath(const std::string & path, const bool front=false);
81 /** 获取的搜索路径的数组。
Gets the array of search paths.
84 virtual const std::vector&std::string&& getSearchPaths() const;
获取可写的路径。
Gets the writable path.
The path that can be write/read a file in
89 virtual std::string getWritablePath() const = 0;
设置可写的路径。
Sets writable path.
93 virtual void setWritablePath(const std::string& writablePath);
设置在无法加载图像时候是否弹出一个消息框。
Sets whether to pop-up a message box when failed to load an image.
97 virtual void setPopupNotify(bool notify);
98 /** 检查在无法加载图像的时候是否弹出一个消息框。
Checks whether to pop up a message box when failed to load an image.
@return True if pop up a message box when failed to load an image, false if not.
102 virtual bool isPopupNotify() const;
文件到ValueMap的内容转换。(将文件中的内容转换成ValueMap类型)
Converts the contents of a file to a ValueMap.
@param filename The filename of the file to gets content.
@return ValueMap of the file contents.
@note This method is used internally.
109 virtual ValueMap getValueMapFromFile(const std::string& filename);
110 /** Converts the contents of a file to a ValueMap.
This method is used internally.
113 virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
写一个内容为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
120 virtual bool writeToFile(ValueMap& dict, const std::string& fullPath);
121 /** 写一个内容为String类型的.plist文件
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
127 virtual bool writeStringToFile(std::string dataStr, const std::string& fullPath);
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
134 virtual bool writeDataToFile(Data retData, const std::string& fullPath);
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
141 virtual bool writeValueMapToFile(ValueMap& dict, const std::string& fullPath);
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
148 virtual bool writeValueVectorToFile(ValueVector vecData, const std::string& fullPath);
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
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);
判断文件是否存在
Checks whether a file exists.
@note If a relative path was passed in, it will be inserted a default root path at the beginning.
@param filename The path of the file, it could be a relative or absolute path.
@return True if the file exists, false if not.
165 virtual bool isFileExist(const std::string& filename) const;
166 /** 获取文件的扩展名是在较低的情况下的后缀(由点从基本文件名隔开)。
Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.
Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.
@param filePath The path of the file, it could be a relative or absolute path.
@return suffix for filename in lower case or empty if a dot not found.
172 virtual std::string getFileExtension(const std::string& filePath) const;
检查路径是否是绝对路径。
Checks whether the path is an absolute path.t.
176 virtual bool isAbsolutePath(const std::string& path) const;
177 /**检查路径是否是一个目录。
Checks whether the path is a directory.
@param dirPath The path of the directory, it could be a relative or an absolute path.
@return True if the directory exists, false if not.
182 virtual bool isDirectoryExist(const std::string& dirPath) const;
创建一个字典目录
Creates a directory.
@param dirPath The path of the directory, it must be an absolute path.
@return True if the directory have been created successfully, false if not.
188 virtual bool createDirectory(const std::string& dirPath);
移除一个目录
Removes a directory.
@param dirPath
The full path of the directory, it must be an absolute path.
@return True if the directory have been removed successfully, false if not.
194 virtual bool removeDirectory(const std::string& dirPath);
移除一个文件
Removes a file.
@param filepath The full path of the file, it must be an absolute path.
@return True if the file have been removed successfully, false if not.
200 virtual bool removeFile(const std::string &filepath);
给指定目录下的文件重命名
Renames a file under the given directory.
@param path
The parent directory path of the file, it must be an absolute path.
@param oldname
The current name of the file.
@param name
The new name of the file.
@return True if the file have been renamed successfully, false if not.
208 virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name);
209 /** 给指定目录下的文件重命名
Renames a file under the given directory.
@param oldfullpath
The current fullpath of the file. Includes path and name.
@param newfullpath
The new fullpath of the file. Includes path and name.
@return True if the file have been renamed successfully, false if not.
216 virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath);
检索文件的大小
Retrieve the file size.
@note If a relative path was passed in, it will be inserted a default root path at the beginning.
@param filepath The path of the file, it could be a relative or absolute path.
@return The file size.
223 virtual long getFileSize(const std::string &filepath);
224 /** 返回的完整路径缓存。
Returns the full path cache.
227 const std::unordered_map&std::string, std::string&& getFullPathCache() const { return _fullPathC }
229 protected CONUT:
231 /** 在字典中使用一个文件的密钥来查找文件名
Dictionary used to lookup filenames based on a key.
It is used internally by the following methods:基于下面的方法在内部使用
std::string fullPathForFilename(const char*);
236 ValueMap _filenameLookupD
237 /** 该Vector容器包含有分辨率文件夹。元素在此向量的低指数,该决议目录优先级越高。
The vector contains resolution folders.
The lower index of the element in this vector, the higher priority for this resolution directory.
241 std::vector&std::string& _searchResolutionsOrderA
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.
246 std::vector&std::string& _searchPathA
资源的默认根路径。
The default root path of resources.
If the default root path of resources needs to be changed, do it in the `init` method of FileUtils‘s subclass.
For instance:
On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init().
Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
254 std::string _defaultResRootP
完整路径缓存。当一个文件被发现,它将被添加到该高速缓存。
The full path cache. When a file is found, it will be added into this cache.
This variable is used for improving the performance of file search.
259 mutable std::unordered_map&std::string, std::string& _fullPathC
260 /**可写路径。
261 * Writable path.
263 std::string _writableP
文件实用的单指针。
The singleton pointer of FileUtils.
267 static FileUtils* s_sharedFileU
#ifndef _FILEUTILSTEST_SCENE_H_
#define _FILEUTILSTEST_SCENE_H_
#include "cocos2d.h"
class fileUtil : public cocos2d::Layer
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);
bool fileUtil::init()
if (!Layer::init())
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);
//设置和获得分辨率的路径;获取某个文件的路径
void fileUtil::testResolutionDirectories(Ref* sender)
//不同的平台的不同的设备它们的分辨率也存在着某些差异
auto fileUtil = FileUtils::getInstance();
//清除缓存,清空所有的缓存
fileUtil-&purgeCachedEntries();
//默认搜索路径,第一次的默认搜索路径是Resource那个文件夹
std::vector&std::string& _defaultSearchPathA
_defaultSearchPathArray = fileUtil-&getSearchPaths();
std::vector&std::string& searchPath = _defaultSearchPathA
//在默认的搜索路径下在添加一个我们自己的搜索路径
searchPath.insert(searchPath.begin(), "Misc");
//设置新的搜索路径为"Misc"
fileUtil-&setSearchPaths(searchPath);
//获得搜索分辨率资源路径
std::vector&std::string& _defaultResolutionsOrderArray = fileUtil-&getSearchResolutionsOrder();
std::vector&std::string& resolutionsOrder = _defaultResolutionsOrderA
//添加分辨率资源路径
//在依次的在下面的文件名路径下依次的查找所要查找的内容
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();
//清除缓存,清空所有的缓存
fileUtil-&purgeCachedEntries();
std::vector&std::string& _defaultSearchPathArray = fileUtil-&getSearchPaths();
std::vector&std::string& searchPaths = _defaultSearchPathA
//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");
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 = _defaultResolutionsOrderA
//添加一个路径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");
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();
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 =
bool isExist =
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());
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`.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
117 virtual void setDataForKey(const char* key, const Data& value);
118 /**调用此函数会将我们所改变的数据保存在.xml文件中去。
119 * You should invoke this function to save values set by setXXXForKey().
121 virtual void flush();
123 * delete any value by key,
124 * @param key The key to delete value.
126 virtual void deleteValueForKey(const char* key);
128 * Returns the singleton.
130 static UserDefault* getInstance();
134 static void destroyInstance();
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
143 static void setDelegate(UserDefault *delegate);
144 /** @deprecated Use getInstace() instead.
146 CC_DEPRECATED_ATTRIBUTE static UserDefault* sharedUserDefault();
147 /**@deprecated Use destroyInstance() instead.
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.
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.
156 static bool isXMLFileExist();
#ifndef _USERDEFAULTTEST_SCENE_H_
#define _USERDEFAULTTEST_SCENE_H_
#include "cocos2d.h"
class userDefault : public cocos2d::Layer
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);
bool userDefault::init()
if (!Layer::init())
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);
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");
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");
CCLOG("bool value is false");
标签:原文地址:http://www.cnblogs.com/geore/p/5799570.html
&&国之画&&&& &&&&chrome插件&&
版权所有 京ICP备号-2
迷上了代码!

我要回帖

更多关于 ob25133x芯片的作用 的文章

 

随机推荐