繁体   English   中英

我应该将sqlite数据库文件写入Documents目录还是Library / Caches?

[英]Should i write sqlite database file to Documents directory or Library/Caches?

我已经阅读了Apple的数据存储指南,并且对于应该在应用程序中创建的sqlite数据库文件的存放位置感到非常困惑。 我想从sqlite文件中读取内容,即使该应用处于离线模式也是如此。 我读到,创建的此类文件应设置为“请勿备份”标志,保存在库/缓存中。 请为我建议正确的做法。

答案取决于如何创建数据库文件:

根据“数据存储准则”页面

  1. 只有用户生成的文档或其他数据,或者应用程序无法以其他方式重新创建的文档和其他数据,才应存储在/ Documents目录中,并由iCloud自动备份。

  2. 可以再次下载或重新生成的数据应存储在/ Library / Caches目录中。 您应放入“高速缓存”目录中的文件示例包括数据库高速缓存文件和可下载内容,例如杂志,报纸和地图应用程序使用的文件。

对我来说,这似乎比较清楚:如果您的应用以编程方式创建了某些内容或生成了要保存的数据,请将其放入“缓存”文件夹中。 如果这是客户自己生成的独特内容(通过键入键盘或他们手动干预并完成的操作),请将其放入“文档”中。

“不备份”表示文件永远不会发送到iCloud,如果文件丢失,则必须从头开始重新创建(或重新安装)。

这可能对您有帮助。 将数据库复制到documents目录就足够了,bundle上的文件是只读的,在某些情况下,如果您需要随时更新,最好的方法是首先复制数据库(如果文件目录中不存在该数据库)。

将数据库复制到documents目录的示例代码如下:

-(void) checkAndCreateDatabase {

    // Setup some globals
    NSString *databaseName = @"AnimalDatabase.sql";

    // Get the path to the documents directory and append the databaseName
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];


    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

    [fileManager release];
}

您可以参考本教程中的文件,文件目录上的内容以读取,写入方式进行,因此您可以从数据库中读取内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM