2016-04-15 94 views
7

我對ios開發很新穎。Swift Realm,以正確的方式加載預填充數據庫?

我遵循這個migration example使用預填充數據庫,並更改代碼有點

這裏是我的AppDelegate -> func application

let defaultPath = Realm.Configuration.defaultConfiguration.path! 
    let path = NSBundle.mainBundle().pathForResource("default", ofType: "realm") 

    if let bundledPath = path { 

     print("use pre-populated database") 
     do { 
      try NSFileManager.defaultManager().removeItemAtPath(defaultPath) 
      try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath) 

     } catch { 
      print("remove") 
      print(error) 
     } 
    } 

我在真實的設備測試這種使用最終代碼。

它可以工作,但根據代碼邏輯,它將始終重置爲預填充數據庫。這已驗證:數據在應用程序重新啓動後重置。我試過moveItemAtPath而不是copyItemAtPath。權限錯誤

我試圖在複製後刪除預填充的數據庫文件。權限錯誤

我試圖使用預先填充的數據庫文件作爲領域的默認配置路徑。錯誤也會發生。

回答

1

是的,你的邏輯是正確的。每次執行此代碼時,Documents目錄中的默認Realm文件都將被刪除,並替換爲應用程序包附帶的靜態副本。這是通過Realm示例代碼中的設計完成的,以便演示每次啓動應用程序時的遷移過程。

如果您只希望這種情況發生一次,最簡單的方法是預先檢查Realm文件是否已存在於默認路徑中,然後僅在不是時才執行復制已經在那裏。 :)

let alreadyExists = NSFileManager.defaultManager().fileExistsAtPath(defaultPath) 

if alreadyExists == false && let bundledPath = path { 
    print("use pre-populated database") 
    do { 
     try NSFileManager.defaultManager().removeItemAtPath(defaultPath) 
     try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath) 

    } catch { 
     print("remove") 
     print(error) 
    } 
} 
+0

哦,是的,這將是一個辦法。順便說一句,它是'fileExistsAtPath' – Jesse

+0

@TiM爲什麼'文件存在'總是返回true? – aaisataev

+0

@aaisataev創建文件後,不需要再次運行相同的替換代碼。所以有意義的是,它會在第一次之後總是返回「true」。 :) – TiM

7

雨燕3.0,試試這個:

let bundlePath = Bundle.main.path(forResource: "default", ofType: "realm") 
    let destPath = Realm.Configuration.defaultConfiguration.fileURL?.path 
    let fileManager = FileManager.default 

    if fileManager.fileExists(atPath: destPath!) { 
     //File exist, do nothing 
     //print(fileManager.fileExists(atPath: destPath!)) 
    } else { 
     do { 
      //Copy file from bundle to Realm default path 
      try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!) 
     } catch { 
      print("\n",error) 
     } 
    } 
+0

您確定「Realm.Configuration.defaultConfiguration.fileURL?.path」在未來版本的領域中不會更改嗎? –

+0

我不確定它在未來是否會發生變化,但現在它工作正常(Realm 2.5.1) –

+0

@LuanVoThanh爲什麼'file exists'總是返回true? – aaisataev