簡體   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