我正在使用 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/