我在一个应用程序中有两个领域文件,当我想要迁移它们时出错了。我希望在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)
}()
}
当我向新闻添加新属性时,例如 @objc dynamic var title:String , 我在AppDelegate func应用程序中添加以下代码(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?= nil) - >布尔
let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in
})
Realm.Configuration.defaultConfiguration = config
返回崩溃时的消息尝试! NewsManager 中的领域(配置:配置)。
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.0iOS:10
答案 0 :(得分:0)
Realm按预期工作。某些类型的模型更改Realm可以自动迁移,其他需要您提供手动迁移。您示例中的一个就是其中之一。
由于您添加了类型为String
的新的非可选属性,因此Realm需要遍历所有现有模型并确定要在该属性中放置的内容。如果属性类型为String?
,则使用nil
作为默认值是有意义的,Realm可以自动执行迁移。但是,由于类型为String
并且没有明显的合理默认值,因此Realm要求您为每个模型对象手动指定新属性的值。
解决此“问题”的正确方法是增加架构编号,并提供一个迁移块,只要您以需要迁移的方式更改模型,就会实际指定新属性的新值。
请查看我们的documentation on migrations了解详情。
答案 1 :(得分:0)
查看https://realm.io/docs/swift/latest/#migrations。 Realm站点非常适合了解如何在项目中正确使用Realm