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

马哈茂德·科威特(Mahmoud Khwaiter)

我正在使用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附加到列表中。有人知道代码中的解决方案吗?

由于您已经有了目标的主键,因此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
    }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章