我有一个类
中定义的领域数据库对象class TPDailyRashifal: Object, Mappable {
public required convenience init?(map: Map) {
self.init()
mapping(map: map)
}
dynamic var rashi: String = ""
dynamic var rashiDetail: String = ""
public func mapping(map: Map) {
rashi <- map["rashi"]
rashiDetail <- map["rashifal"]
}
override static func primaryKey() -> String {
return "rashi"
}
}
我想在我的对象中添加这三个变量,如下所示
dynamic var date: String = ""
dynamic var fallIds: String = ""
dynamic var rating: Int = 0
我知道我的映射函数必须修改并添加以下内容。
date <- map["date"]
fallIds <- map["fallIds"]
rating <- map["rating"]
但我的
dynamic var rashi: String = ""
定义必须更改为
dynamic var rashi: Int = 0
在我的Appdelegate
,applicationDidFinishLaunchingWithOptions
函数中,我写了
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
print("Schema Version 0")
// The enumerateObjects(ofType:_:) method iterates
// over every Person object stored in the Realm file
migration.enumerateObjects(ofType: TPDailyRashifal.className()) { oldObject, newObject in
// combine name fields into a single field
/*
To add these variables during migration
dynamic var date: String = ""
dynamic var fallIds: String = ""
dynamic var rating: Int = 0
*/
let oldRashi = oldObject?["id"] as? Int
// let newRashiId =
}
}
})
我很困惑,我应该在哪里开始在Realm对象中添加新变量。我已提到其他问题,但我无法赶上它们。
答案 0 :(得分:0)
我相信你需要将你的“rashi”重命名为其他东西(假设在下面的例子中新的Int将是“rashi2”)。
migration.enumerateObjects(ofType: TPDailyRashifal.className()) { oldObject, newObject in
newObject!["date"] = ""
newObject!["fallIds"] = ""
newObject!["rating"] = 0
newObject!["rashi2"] = 0 // this version has a rashi2 (Int) instead of a rashi (String).
}
另请注意,如果需要通过string-to-int转换将旧rashi转换为rashi2,可以通过在此闭包中使用oldObject [“rashi”]来获取旧字符串,然后转换它并将rashi2设置为它而不是0。
答案 1 :(得分:0)
Smarcat
部分正确但后来我不得不做一些研究,现在就是。
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
print("Schema Version 0")
// The enumerateObjects(ofType:_:) method iterates
// over every Person object stored in the Realm file
migration.enumerateObjects(ofType: TPDailyRashifal.className()) { oldObject, newObject in
// combine name fields into a single field
newObject!["date"] = ""
newObject!["fallIds"] = ""
newObject!["rating"] = 0
newObject!["rashi2"] = 0
}
migration.renameProperty(onType: TPDailyRashifal.className(), from: "rashi", to: "rashi2")
}
})
我必须使用migration.renameProperty
块将rashi
重命名为rashi2
。