【问题标题】:How to migrate multiple realm files in one App如何在一个 App 中迁移多个领域文件
【发布时间】:2018-04-14 16:34:27
【问题描述】:

我在一个应用程序中有两个领域文件,当我想迁移它们时出现问题。我希望在 Xcode 中运行时自动更新领域,而不是每次都更改 schemaVersion

class News: Object {
    @objc dynamic var name: String  
}

class NewsManager {
    static var realm = try! Realm()
    static var cacheRealm: Realm = {

        let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
                                                         appropriateFor: nil, create: false)
        let url = documentDirectory.appendingPathComponent("cache.realm")
        var config = Realm.Configuration()
        config.fileURL = url
        return try! Realm(configuration: config)
    }()
}

当我向 News 添加一个新属性时,例如 @objc dynamic var title: String, 我在 AppDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool

中添加以下代码
let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in

    })
Realm.Configuration.defaultConfiguration = config

返回尝试崩溃的消息! NewsManager 中的领域(配置:config)

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:
- Property 'News.test' has been added." UserInfo={Error Code=10, NSLocalizedDescription=Migration is required due to the following errors:
- Property 'News.test' has been added.}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.69.2/src/swift/stdlib/public/core/ErrorType.swift, line 181

我该怎么办?

领域:3.0.1

斯威夫特:4.0

iOS:10

【问题讨论】:

    标签: ios swift realm


    【解决方案1】:

    查看https://realm.io/docs/swift/latest/#migrations。 Realm 网站非常适合了解如何在您的项目中正确使用 Realm

    【讨论】:

      【解决方案2】:

      领域正在按预期工作。某些类型的模型更改 Realm 可以自动迁移,其他类型要求您提供手动迁移。您的示例中的那个就是其中之一。

      由于您添加了一个新的、非可选的 String 类型的属性,Realm 需要检查您现有的所有模型并确定要在该属性中放入什么。如果属性类型为String?,则使用nil 作为默认值是有意义的,Realm 可以自动执行迁移。但是,由于类型是 String 并且没有明显的合理默认值,Realm 要求您手动为每个模型对象的新属性指定一个值。

      解决此“问题”的正确方法是增加您的架构编号并提供一个迁移块,当您以需要迁移的方式更改模型时,该块实际上为新属性指定新值。

      请查看我们的documentation on migrations 了解更多详情。

      【讨论】:

      • 我添加了 @objc dynamic var title: String?@objc dynamic var title: String = "",它也在 cache.realm。所以我必须在添加新属性后使用 Xcode 运行时增加 schemaVersion?
      • 如果您进行需要迁移阻止的更改,例如添加新的非可选属性,则需要增加schemaVersion
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多