如何在嵌套的领域列表中创建新对象?父对象应保持不变,但必须将其"holds"添加到的列表



我使用Swift 3和Xcode 8。

我想做的是一个存储"用户"的笔记应用程序,然后存储链接到用户的"笔记"。这是相关代码。

My Main user Model:

class Person: Object {
    dynamic var dateOfUpdatingNote: NSDate?
    dynamic var addIndex: Int = 0
    let notes = List<Notes>()
    override static func primaryKey() -> String? {
    return "addIndex"
  }
 }

我的主要笔记模型:

class Notes: Object {
    dynamic var NoteText: String?
    dynamic var dateofCreation: NSDate?
    dynamic var dateofUpdate: NSDate?
    dynamic var noteImage: NSData?
}

我已经编写了一些可以识别正确用户的代码,然后更新user存储的Notes。这不是我想要实现的。我想让用户创建一个新注释,然后将其添加到Users List

下面是我引用的代码:

    var currentPersonIndex = 0 //Basically holds the indexPath.row of the selected User
    @IBAction func noteInputButtonDidPress(_ sender: UIButton) {
    if let words = noteInputTextField.text {
        let realm = try! Realm()
        try! realm.write {
            realm.create(Person.self, value: ["addIndex": currentPersonIndex, "notes": [["noteImage": nil, "dateOfUpdate": nil, "NoteText": words, "dateOfCreation": nil]]], update: true)
        }
        noteInputTextField.text = nil
    }
}

这实际上更新了Notes,但我根本不知道如何将一个全新版本的Notes添加到List中。有人知道解决这个问题的代码吗?

既然您已经获得了目标User的主键,那么您可以使用realm.object(ofType:forPrimaryKey:)查询它。一旦你有了这个对象,你就可以在写事务中添加新的Note对象。

@IBAction func noteInputButtonDidPress(_ sender: UIButton) {
    if let words = noteInputTextField.text {
        let realm = try! Realm()
        let person = realm.object(ofType: Person.self, forPrimaryKey: currentPersonIndex)
        let newNote = Note()
        let newNote.NoteText = words
        try! realm.write {
            person.notes.append(newNote)
        }
        noteInputTextField.text = nil
    }
}

有什么难的?只需获取包含您想要编辑的notesPerson对象,然后编辑它,然后执行realm.add(personObject, update:true)