我正在使用Qt5.2在iPhone上编写一个应用程序。当应用程序运行时,我希望将用户输入的一些信息保存到一个文件中,这样下次用户启动应用程序时,他将拥有保存的信息。
我试着这样做:
QString cur_dir = QDir::currentPath();
QString init_file = cur_dir+"/init.xml";
QSettings settings( init_file, QSettings::IniFormat );
settings.setValue("General/SavedVariable", sel_label->text() );但当我验证执行此操作时,该文件尚未创建:
if( !QFileInfo( init_file ).exists() )
std::cout << "FILE DOES NOT EXISTS " << std::endl;
else
std::cout << "FILE EXISTS " << std::endl;发布于 2014-02-02 07:50:53
我找到了一个解决方案。您不能将文件保存在Bundle目录中。您必须保存在Documents目录中。下面是我用来做这件事的代码:
{
QString cur_dir = QDir::currentPath();
int found = cur_dir.lastIndexOf( "/" );
QString leftSide = cur_dir.left(found+1);
leftSide += "Documents";
init_file = leftSide+"/init.xml";
if( !QFileInfo( init_file ).exists() )
writeConfig();
else
readConfig();
}
void
writeConfig( void )
{
QSettings settings( init_file, QSettings::IniFormat );
settings.setValue("General/SavedVariable", sel_label->text() );
}
void
readConfig( void )
{
QSettings settings( init_file, QSettings::IniFormat );
QString save_var = settings.value( "General/SavedVariable" ).toString();
sel_label->setText( save_var );
}这是一种方法。您还可以向您的项目添加一个目标C文件.mm到您的qt项目,并直接获得文档路径。
NSString *rootPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,
NSUserDomainMask,
YES) objectAtIndex:0];发布于 2016-04-02 14:39:36
实际上,在IOS中,你不能将你的文件保存在当前目录下(检查一下this也不错)。我使用了QStandardPaths类,并编写了以下代码来使其跨平台:
QString path = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value(0);
QDir myDir(path);
if (!myDir.exists()) {
myDir.mkpath(path);
}
QDir::setCurrent(path);现在,可以在当前目录中创建文件或目录。
发布于 2016-06-27 03:46:30
允许/期望应用程序写入iOS文档目录。此处写入的数据是永久性的,将在iTunes备份过程中进行备份。
#include <QStandardPaths>
QFile myfile(QStandardPaths::writableLocation(QStandardPaths::HomeLocation).append("/Documents/mystuff.txt"));
myfile.open(QIODevice::ReadWrite);https://stackoverflow.com/questions/21367475
复制相似问题