一:UserDefault
UserDefault是一个单例,通过:UserDefault::getInstance();来获取这个类的实例。
UserDefault使用哈希表结构,Key-Value,Key--索引,Value--值。
代码如下:
//UserDefault
UserDefault::getInstance()->setBoolForKey("bool", true);
UserDefault::getInstance()->setIntegerForKey("score", 5000);
bool b = UserDefault::getInstance()->getBoolForKey("bool");
log("%d",b);
int j = UserDefault::getInstance()->getIntegerForKey("score");
log("%d",j);
std::string path = UserDefault::getInstance()->getXMLFilePath();//获取可读可写的文件路径
log("%s",path.c_str());
bool c = UserDefault::getInstance()->isXMLFileExist();
log("%d",c);//0?
二:文件路径
应用程序中的cpp文件是只读的,如果我们要修改文件,需要将文件拷贝到一个可读,可写的文件夹下,然后再做修改。
代码如下:
//获取文件路径
std::string path = FileUtils::getInstance()->getWritablePath();//获取可写路径
log("%s",path.c_str());
path += "co.txt";//拼接路径
std::string data;
if (!FileUtils::getInstance()->isFileExist(path)) {//判断路径是否存在
data = FileUtils::getInstance()->getStringFromFile("co.txt");//获取.txt文件中的内容
log("%s",data.c_str());
FILE* file = fopen(path.c_str(), "w");//打开文件,如果不存在,则创建一个空的文件
fputs(data.c_str(), file);//写入
fflush(file);//清除缓存
fclose(file);//关闭
}else{
data = FileUtils::getInstance()->getStringFromFile(path);
log("%s",data.c_str());
}
//标签显示
auto label = Label::createWithTTF(data,"fonts/Marker Felt.ttf",50);
label->setPosition(Vec2(600,600));
this->addChild(label);
//修改内容
FILE* changeFile = fopen(path.c_str(), "w");
fputs("gss", changeFile);
fclose(changeFile);
下一篇 数据解析(json,xml)