gpt4 book ai didi

ios - Realm 迁移没有充分记录。谁能澄清一下?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:36:51 24 4
gpt4 key购买 nike

在 Realm 数据库上执行迁移的文档很少,文档似乎已经过时。有两个方面解释了如何迁移数据:

-- Realm 网站上的简单示例:https://realm.io/docs/swift/latest/

-- Github 示例部分中更详细的示例:https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-3.0/Migration/AppDelegate.swift

这些示例都没有充分说明如何在架构版本之间迁移数据。我试过尝试这些示例,但尚未进行任何迁移。同样,在升级到没有模式更改和数据更改的较新 Realm 版本时,我遇到了应用程序崩溃的问题,这不会发生在模拟器中,而是在从 TestFlight 或 App Store 安装应用程序时发生。

似乎 Realm 文档和详细介绍迁移的示例需要更新。我感兴趣的 Realm 是:

  1. 升级到较新的 Realm 版本,而无需更改数据库中的架构。不清楚我是应该继续使用以前版本生成的 default.realm 文件,还是需要使用更新的 Realm 框架版本重新生成 default.realm 文件。

  2. 向 Realm 对象添加新属性。

  3. 将新对象(“行”)添加到现有类而无需更改任何架构。

  4. 没有对数据库中现有类的架构进行更改,而是添加了一个或多个全新的类。

  5. 以上任意组合。

谢谢!

最佳答案

抱歉,文档还不够。我们感谢反馈并将使用它来改进它们。同时,让我回答您的问题:

  1. 升级 SDK 时无需执行任何操作。有时,我们会升级核心数据库文件格式,但这种迁移会在您打开 Realm (Realm()) 时自动发生,因此您不必担心。
  2. 当您向对象添加新属性时,您只需遵循此代码段即可。

迁移 block 中不需要任何内容​​,因为此 block 只是在版本之间应用数据转换。您需要做的就是增加 schemaVersion

// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 1,

// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
})

// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()
  1. 将对象添加到 Realm 不会影响架构,因此迁移不相关。
  2. 这与 2 相同,您只需增加 schemaVersion,但您不必在迁移 block 中执行任何操作,因为 Realm 会处理所有事情。迁移 block 用于自定义迁移逻辑,例如,您希望将 firstNamelastNameschemaVersion=0 转换为 fullName 当更新到 schemaVersion=1 时。在这种情况下,您可以从旧版本中获取数据并将字符串连接到迁移 block 中的新 fullName 属性中。

希望对您有所帮助!

关于ios - Realm 迁移没有充分记录。谁能澄清一下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com