如何在嵌套的Realm List中创建新对象?父对象应保持不变,但必须添加“保持”的列表

时间:2016-11-15 11:18:27

标签: ios swift realm

我正在使用Swift 3和Xcode 8。

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

我的主要用户型号:

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?

}

我编写了一些可以识别正确用户的代码,然后更新用户存储的Notes。这不是我想要完成的。我想要的是让用户创建一个新的音符,然后将其附加到用户列表

这是我所指的代码:

    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中。有没有人知道代码中的解决方案?

2 个答案:

答案 0 :(得分:1)

由于您已获得目标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
    }

}

答案 1 :(得分:0)

怎么这么难?只需抓取包含您要编辑的Person的{​​{1}}对象,然后对其进行修改,然后执行notes