我正在像这样初始化我的 Realm 实例:

private static let sUserRealm:Realm = try! Realm(configuration:Realm.Configuration(
        fileURL: Bundle.main.url(forResource: "user" ,withExtension: "realm"),
        inMemoryIdentifier: nil,
        syncConfiguration: nil,
        encryptionKey: nil,
        readOnly: false,
        schemaVersion: 0,
        migrationBlock: sMigrationBlock,
        deleteRealmIfMigrationNeeded: true,
        objectTypes: nil))

但是,我收到此错误:
fatal error: A Realm Configuration must specify a path or an in-memory
identifier.: file /Users/realm/workspace/Package iOS Swift/tightdb_objc/RealmSwift/RealmConfiguration.swift, line 201

所有 Realm 在关于创建多个 Realm 的 swift 文档中都有 this 示例,即使逐字复制也会引发相同的错误。如何创建和访问 Realm 文件?

最佳答案

Bundle.url(forResource:withExtension:) 返回给定包中现有文件的路径。您链接到的 Realm 文档部分使用了在应用程序包中包含 Realm 文件的示例。

由于看起来您正在尝试在特定路径上创建新的 Realm 文件,因此您应该计算该路径并将其设置为 fileURL 上的 Realm.Configuration 。您通常不想为此使用 Bundle API,因为应用程序包中的文件不可写。相反,您应该构建一个相对于应用程序文档或缓存目录的路径:

let documentDirectory = FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
                                                appropriateFor: nil, create: false)
let url = documentDirectory.appendingPathComponent("my-new-realm.realm")

关于ios - 如何创建自定义 Realm 文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41977952/

10-16 14:42