2017-04-21 86 views
0

我想複製預裝的境界文件,所以我做的:境界FILEEXISTS始終是真實的

複製我的文件,以項目導航命名default.realm。然後檢查是否fileExists:

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("File exist") 
} else { 
    do { 
     //Copy file from bundle to Realm default path 
     try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!) 
     print("Copied") 
    } catch { 
     print("\n",error) 
    } 
} 

,它總是返回true,所以我不能複製我的境界文件。

+1

你有代碼'let realm = try! Realm()'作爲視圖控制器中的一個實例變量?視圖控制器在Storyboard BEFORE'didFinishLaunchingWithOptions'中實例化。請確保並修改它們到'lazy var realm = try! Realm()',然後從模擬器中刪除應用程序,然後重新嘗試。 –

+0

@kishikawakatsumi非常感謝你。所有問題都在'let'! – aaisataev

回答

2

我在重置內容和設置(Simulator > Reset Content and Settings...)後,在模擬器中運行了您的代碼,它似乎按預期執行。

如果您以前在項目中使用過Realm(即測試),則可能會看到舊的default.realm文件。

+0

我重置了內容和設置,它仍然返回'文件存在'。 Realm如何以及在哪裏創建一個新的'default.realm'文件?似乎我檢查文件是否存在領域創建默認文件後存在。我檢查了'didFinishLaunchingWithOptions'。 – aaisataev

+0

然後第二個問題是我幾乎沒有複製我的領域文件,「let realm = try! Realm()'返回空結果... – aaisataev