5 migration realm ios swift realm-migration
我复制并粘贴了领域文档中的代码。但不知道如何更改我在旁边评论的部分以表示。(在底部)以下是我收到的完整错误消息:
初始化 newrealm 时出错,错误域 = io.realm 代码 = 10 “由于以下错误,需要迁移: - 已添加属性 'Item.dateCreated'。” UserInfo={NSLocalizedDescription=Migration is required 由于以下错误: - Property 'Item.dateCreated' has been added., Error Code=10} 2018-07-30 21:25:24.231575-0400 Todoey[87561:3063712] * ** 由于未捕获的异常“RLMException”而终止应用程序,原因:“类别“类别”的“无效的属性名称”“dateCreated”。”
以下是我尝试迁移的女巫代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print(Realm.Configuration.defaultConfiguration.fileURL)
do {
let realm = try Realm()
} catch {
print("error initializing newrealm, \(error)")
}
//Migration
let config = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
migration.enumerateObjects(ofType: Category.className()) { (old, new) in
new!["dateCreated"] = Date()
}
migration.enumerateObjects(ofType: Item.className()) { (old, new) in
new!["dateCreated"] = Date()
}
}
})
Realm.Configuration.defaultConfiguration = config
//Migration X
return true
}
Run Code Online (Sandbox Code Playgroud)
问题似乎出现在“//将名称字段合并为单个字段”注释所在的位置。我需要将这些值更改为以下内容:
class Item: Object {
@objc dynamic var title: String = ""
@objc dynamic var done: Bool = false
@objc dynamic var dateCreated = NSDate() //this is the new data
var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}
Run Code Online (Sandbox Code Playgroud)
问题是已添加到领域数据库的新属性。
当您在模拟器中运行应用程序时,它将拉出没有此新属性的旧领域数据库。
在 Xcode 10、Swift 4.2 中工作的解决方案:
注意:当应用程序仍处于开发阶段并使用模拟器时,此解决方案非常有用。如果您的应用程序已经发布并投入生产,那么您应该增加数据库的架构版本。Realm 网站上有指导如何做到这一点。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
3222 次 |
| 最近记录: |