我查看了Realm网站上的文档,找不到任何描述如何在迁移中处理删除属性的内容。我采用了一组彼此非常相似的属性,并将它们移至新对象。像这样:
class MyObject: Object {
@objc dynamic var siteName = ""
@objc dynamic var lat = 0.0
@objc dynamic var lon = 0.0
@objc dynamic var roadNames = ""
@objc dynamic var startTime = ""
@objc dynamic var endTime = ""
@objc dynamic var comments: String = ""
@objc dynamic var complete: Bool = false
}
然后我将其更改为:
class Site: Object {
@objc dynamic var siteName = ""
@objc dynamic var lat = 0.0
@objc dynamic var lon = 0.0
@objc dynamic var roadNames = ""
}
class MyObject: Object {
@objc dynamic var site: Site?
@objc dynamic var startTime = ""
@objc dynamic var endTime = ""
@objc dynamic var comments: String = ""
@objc dynamic var complete: Bool = false
}
我的移民是
let block: MigrationBlock = { (migration: Migration, oldSchemaVersion) in
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: MyObject.className()) { oldObject, newObject in
newObject!["siteName"] = oldObject!["siteName"]
newObject!["lat"] = oldObject!["lat"]
newObject!["lon"] = oldObject!["lon"]
newObject!["roadNames"] = oldObject!["roadNames"]
// Delete old properties.
}
}
}
我的迁移应如何删除属性?
答案 0 :(得分:1)
如果阅读Realm guide on migrations,您会在其中一个代码块的注释中看到它说:
// Nothing to do! // Realm will automatically detect new properties and removed properties // And will update the schema on disk automatically
因此您不必担心删除属性,因为它们会自动删除。
不过,您需要担心的是如何迁移其他值。您应该为每个Site
创建一个MyObject
并为该Site
分配属性,我在这里看不到您在做的事情。有关如何在迁移块中创建新的Site
的信息,请参见this question。
您的迁移块应类似于:
migration.enumerateObjects(ofType: MyObject.className()) { oldObject, newObject in
let site = migration.create(Site.className())
site["siteName"] = oldObject!["siteName"]
site["lat"] = oldObject!["lat"]
site["lon"] = oldObject!["lon"]
site["roadNames"] = oldObject!["roadNames"]
newObject!["site"] = site
}