gpt4 book ai didi

ios - 如何在一个应用程序中迁移多个 Realm 文件

转载 作者:行者123 更新时间:2023-11-30 12:02:15 25 4
gpt4 key购买 nike

我在一个应用程序中有两个 Realm 文件,当我想迁移它们时出现问题。我希望在 Xcode 中运行时自动更新 Realm ,而不是每次都更改 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)
}()
}

当我向新闻添加新属性时,例如@objc动态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 中的 Realm (配置: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

我应该做什么?

Realm :3.0.1

swift :4.0

iOS:10

最佳答案

Realm 正在按预期运行。某些类型的模型更改 Realm 可以自动迁移,而其他类型的模型更改则需要您提供手动迁移。您的示例中的就是其中之一。

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

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

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

关于ios - 如何在一个应用程序中迁移多个 Realm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47070443/

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