从 Bundle 复制一个 Realm 到 Documents,然后将它读入一个本地常量,在 Swift 2.0

Copy a Realm from Bundle to Documents, then read it into a local constant, in Swift 2.0

好的,所以我在 Swift 2.0 项目的捆绑包中构建了一个预填充的 Realm。我试图在第一次启动时将它复制到我的文档目录,然后从该位置读取它并从那里使用它。看起来我已经写入了 Documents,但是 Realm 不会读入我的 let。这是我保存它的方式(这会在磁盘上创建文件,所以我认为一切都很好):

final func copyEmptyDatabaseIfRequired() {
    let documentsPath: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).first!
    let storePath: String = documentsPath.stringByAppendingPathComponent("OohRealm.realm")

    if !NSFileManager.defaultManager().fileExistsAtPath(storePath) {
        let defaultStorePath : String! = NSBundle.mainBundle().pathForResource("OohRealm", ofType: "realm")
        do {
            try NSFileManager.defaultManager().copyItemAtPath(defaultStorePath, toPath: storePath)
        } catch _ {
            // Handle nasty goings-on later. No really.
        }
    }
}

这就是我尝试将该文件读入我的数据管理器中的本地 let 的方式(这是行不通的,我点击了 catch 和我的 realmnil:

let fileManager = NSFileManager.defaultManager()
let documentsURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let realmURL = documentsURL.URLByAppendingPathComponent("OohRealm.realm")

do {
    realm = try Realm(path: realmURL.absoluteString)
} catch {
    //
}

我遇到的一个绊脚石是,在 Swift 2.0 中,Apple 确实希望您使用 URL 而不是字符串与文件系统进行交互,但 Realm 希望我提供它path 作为字符串。这是一个棘手的问题。

我可能做错了什么?

尝试改变这个

realm = try Realm(path: realmURL.absoluteString)

至此

realm = try Realm(path: realmURL.path!)

NSUrls 旨在表示通用 URLs,并且可以引用文件以外的内容。 absoluteString 属性 也可以标识前缀中此 URL 的资源类型。对于文件,它以前缀 file:// 开头。此前缀字符串不适合与 NSFileManagerNSPathUtilities 等文件系统库一起使用。显然它也不适合 Realm

如果您知道您正在处理文件 URL,NSUrl 会为您提供 path 属性,这是文件的绝对路径,并且是适用于文件系统库。

顺便说一句,文件系统库是 path 的用途之一,但不是唯一目的。