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

标签 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?

}

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

这是我指的代码:

    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
    }

}

这实际上更新了注释,但我根本不知道如何将全新版本的注释附加到列表中。有谁知道代码中的解决方案吗?

最佳答案

因为您已经获得目标 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
    }

}

关于ios - 如何在嵌套的 Realm 列表中创建新对象?父对象应保持不变,但必须将其 "holds"添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40608519/

相关文章:

ios - 将 GMSMarker 移动 X 米偏转

ios - Realm 不想更新 RLMObject 属性的值

ios - 在 SceneKit 中,从 scene.rootNode 中删除 SCNNode 节点会导致崩溃

ios - 在 UICollectionView 中检测触摸

iphone - 如何在 iOS 上的 AVPlayer 或 MPMoviePlayerController 中选择音频 channel ?

ios - 在 Collection View 中列出照片

ios - 以编程方式创建 UIViews 在 Xcode 11.1 中不起作用

ios - 无法与谷歌地图中的自定义信息窗口交互

java - Realm 数据库不写数据

swift - 如何根据 bool 属性对 Realm 结果进行排序