我在一个应用程序中有两个领域文件,当我想要迁移它们时出错了 . 我希望在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
return try! Realm(configuration: config) 中 return try! Realm(configuration: 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
2 回答
看看https://realm.io/docs/swift/latest/#migrations . Realm站点非常适合理解在项目中如何正确使用Realm
Realm按预期工作 . 某些类型的模型更改Realm可以自动迁移,其他类型则要求您提供手动迁移 . 您的示例中的一个是其中之一 .
由于您添加了一个类型为
String
的新的非可选属性,因此Realm需要遍历所有现有模型并确定要在该属性中放置的内容 . 如果属性类型为String?
,则使用nil
作为默认值是有意义的,并且Realm可以自动执行迁移 . 但是,由于类型为String
并且没有明显的合理默认值,因此Realm要求您为每个模型对象手动指定新属性的值 .解决此“问题”的正确方法是增加架构编号,并提供一个迁移块,只要您以需要迁移的方式更改模型,就会实际指定新属性的新值 .
请查看我们的documentation on migrations了解更多详情 .