将生成的值添加到RealmObject

时间:2016-07-02 12:47:25

标签: realm kotlin

我在Realm中创建了一个模型如下:

 
open class Contact() : RealmObject() {

    @PrimaryKey
    @Required
    open var id: String = ""

    @Required
    @Index
    open var firstName: String = ""
    @Required
    @Index
    open var lastName: String = ""
    @Required
    @Index
    open var fullName: String = ""

    ...
}
 

更新对象时如何生成fullName

我知道在CoreData中你可以在调用willSave:_时改变属性。这对Realm有什么用?

我尝试过提供一个getter,但这会破坏RealmObject的行为。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用custom setters in RealmObjects

@Required
@Index
open var firstName: String = ""
    set(value) {
        field = value
        updateFullName()
    }

@Required
@Index
open var lastName: String = ""
    set(value) {
        field = value
        updateFullName()
    }

private fun updateFullName() {
    fullName = "$firstName $lastName"
}

@Required
@Index
open var fullName: String = ""