我知道周围有很多类似的问题 - 我担心我的问题处于如此基本的水平,以至于我能找到的所有其他问题都要复杂得多,但似乎并不能完全回答这个问题。
我正在我的日记应用程序中实现“设置”- 我需要让用户能够编辑(除其他外)日记的名称。
要了解我的问题:对于应用程序的初学者,您有一个包含所有当前日记的 tableView - 然后当您输入特定日记时,您可以在此处找到“设置”以编辑该特定日记。
在这里,当单击名为“Diary Name”的 tableViewCell 时,您输入一个简单的 viewController,其中包含一个 textField(保存您当前的日记名称)和一个按钮,该按钮将弹出您并将日记名称更改为新的输入文本域。
这是我在这个“保存按钮”上的当前代码:
@IBAction func saveChanges(_ sender: Any) {
let newDiaryName = Diaries() // Here, I need to reach the specific diary that we are currently editing!
diary?.diaryName = changeDiaryNameTextField.text!
let realm = try! Realm()
try! realm.write {
realm.add(newDiaryName)
}
self.navigationController?.popViewController(animated: true)
}
}
所以我很抱歉,但我是这个世界上的新人......
我的问题是:我到底是怎么到达我此时所在的特定日记的? - 当想要更新一个对象时,这个函数是否适合使用?
回到第一个带有所有日记列表的 tableView,我已经像这样保存了日记:
(所以我猜一本日记类似于 allDiaries[indexPath].. 但我如何从整个其他 viewController 中获取它?)
let allDiaries: Results<Diaries>
required init?(coder aDecoder: NSCoder) {
let realm = try! Realm()
allDiaries = realm.objects(Diaries.self).sorted(byKeyPath: String("dateCreated"), ascending: false)
super.init(coder: aDecoder)
}
抱歉解释的太长了,否则我不知道怎么问!
谢谢!
最佳答案
假设您保存名称的 Dairy
View Controller 是 DairyViewControll,并且您从 DairiesViewController 打开它。
因为我不知道你展示它或推送(Storyboard segue)我会展示这两种情况。
主要思想是在出现之前分配您的乳品对象。
class DairiesViewController: UIViewController {
//open selected dairy, the first option if you present it, second via segue
1. present
func openDairy(diary: Dairy) {
let storyboard = UIStoryboard(name: "main", bundle: nil) //please make sure your storyboard is "main" otherwise change name
let dairyVC = storyBoard.instantiateViewController(withIdentifier: "dairyIdentifier") as! DairyViewControll
dairyVC.dairy = dairy
self.present(dairyVC, animated: true, completion: nil)
}
}
2. via segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dairyVC = segue.destination as! DairyViewControll
dairyVC.dairy = self.dairy // holds selected dairy
}
class DairyViewControll: UIViewController {
let dairy: Dairy! // the dairy user selects to edit
@IBAction func saveChanges(_ sender: Any) {
// you save method is here
}
}
关于ios - 更新 RealmSwift 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222815/