如何在 RealmSwift 中附加嵌套对象?

How to append nested-object in RealmSwift?

这是我的模型,我想在添加新数据时扩展“todos”:

import Foundation
import RealmSwift

class TodoData: Object {
    @objc dynamic var date: String = ""
    @objc dynamic var isToday: Bool = true 
    let todos: List<Todo> = List<Todo>()

    override public static func primaryKey() -> String? {
        return "date"
    }

    convenience init(date: String) {
        self.init()
        self.date = date
        self.isToday = isToday
    }
}

class Todo: Object {
    @objc dynamic var dateInt: Int = 0
    @objc dynamic var title: String = ""
    @objc dynamic var content: String = ""
    @objc dynamic var isDone: Bool = false



    let ofTodo = LinkingObjects(fromType: TodoData.self, property: "todos")

    convenience init(dateInt: Int,title: String, content: String, isDone: Bool) {
        self.init()
        self.dateInt = dateInt
        self.title = title
        self.content = content
        self.isDone = isDone
    }
}

例如。从文本字段 ipnut 文本添加新数据时,主要待办事项数据将被覆盖。 那么我该如何实现 append new Todo 而不被更新呢?

try! self.realm.write {
    let main = TodoData(date: now)
    let sub = Todo(dateInt: todayInt, title: title, content: content, isDone: isDone)
            
                            
    main.todos.append(sub)
    self.realm.add(main, update: Realm.UpdatePolicy.all)
}

保存 Realm 的步骤太多了,让我们简化一下吧!

让我们用一个有狗的 PersonClass 来设置它

class PersonClass: Object {
   @objc dynamic var name = ""
   list dogList = List<DogClass>()
}

然后是 DogClass,它使用 linkingObject 作为返回其所有者的路径

class DogClass: Object {
   @objc dynamic var name = ""
   let linkingPerson = LinkingObjects(fromType: PersonClass.self, property: "dogList")

然后实例化一个人和一只狗并将狗添加到persons列表

let person = PersonClass()
person.name = "Jay"

let dog = DogClass()
dog.name = "Rover"

person.dogList.append(dog)

let realm = try! Realm()
try! realm.write {
   realm.add(person) //this add the person *and* the dog to Realm
}

那么为了解决你的问题,假设稍后我们的人养了一只新狗

让我们加载这个人

let realm = try Realm()
let person = realm.objects(PersonClass.self).filter("name == 'Jay'").first!

然后创建狗

let anotherDog = DogClass()
anotherDog.name = "Spot"

然后,这是重要的一点,将狗添加到 write 中的 person,这会将狗添加到 Realm 并将其添加到 persons 列表中- 全部在一个声明中。

try! realm.write {
   person.dogList.append(anotherDog)
}

请注意,您不应该这样做 .first! 但为了简洁起见,我在这个答案中这样做了。您应该始终安全地处理和解包可选值。

自己回答

try! self.realm.write {
            
    let sub = Todo(title: title, content: content, isDone: isDone)
            
    if let old = self.realm.objects(TodoData.self).filter("dateInt == \(todayInt)").first {
        old.todos.append(sub)
    } else {
        let main = TodoData(date: now, dateInt: todayInt)
        main.todos.append(sub)
        self.realm.add(main, update: Realm.UpdatePolicy.all)
    }
}