在Realm Swift中保存父子对象

时间:2019-03-14 14:18:10

标签: swift realm relationship

我有以下Realm模型和一个提供程序类,用于将数据保存到realm db。

这应该保存RealmFormPaletteRealmParentPaletteRealmTextPalette的数据。但是它只保存前2个数据,即RealmFormPaletteRealmParentPalette

我创建了RealmTextPalette,以在RealmParentPalette上添加一些属性。像这样,我创建了更多具有最小值和最大值的调色板,例如RealmDatePaletteRealmNumberPalette

class RealmFormPalette: RealmBaseModel {
    @objc dynamic var projectId = ""
    @objc dynamic var formId = ""
    @objc dynamic var imageRoute: String?
    let palettes = List<RealmParentPalette>()

    static func from(_ domainObj: FormFieldDomainObj) -> RealmFormPalette {
        let model = RealmFormPalette()
        model.projectId = domainObj.projectId
        model.formId = domainObj.formId
        model.imageRoute = domainObj.imageRoute

        for paletteDomainObj in domainObj.palettes {
            let palette = RealmTextPalette.from(paletteDomainObj as! TextPaletteDomainObj)
            model.palettes.append(palette.palette!)
        }

        return model
    }
}

class RealmParentPalette: RealmBaseModel {
    @objc dynamic var fieldId = ""
    @objc dynamic var type = ""
    @objc dynamic var question = ""

    static func from(_ object: ParentPaletteDomainObj) -> RealmParentPalette {
        let model = RealmParentPalette()
        model.fieldId = object.fieldId
        model.type = object.type
        model.question = object.question
        return model
    }
}


class RealmTextPalette: Object {
    let maxLength = RealmOptional<Int>()
    @objc dynamic var palette: RealmParentPalette?

    static func from(_ object: TextPaletteDomainObj) -> RealmTextPalette {
        let model = RealmTextPalette()
        model.palette = RealmParentPalette.from(object)
        model.maxLength.value = object.maxLength
        return model
    }
}

class FormFieldDbProvider {
    func insert(form: FormFieldDomainObj) {
        try! getInstance().write {
            getInstance().add(RealmFormPalette.from(form))
        }
    }
}

0 个答案:

没有答案