更新RealmSwift中的对象?

时间:2018-11-09 09:15:21

标签: ios swift realm updates

我知道周围有很多类似的问题-我担心我的问题在这样的基本层面上,我能找到的所有其他问题都更加复杂,但似乎并不能完全回答这个问题。

我正在日记应用程序中实现“设置”-我需要让用户能够(除其他事项外)编辑日记的名称。

要理解我的问题:对于应用程序中的入门者,您具有一个带有所有当前日记的tableView-然后,当您输入特定日记时,可以在其中找到“设置”以编辑此特定日记。

在这里,单击名为“日记名称”的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)
}

很抱歉,冗长的解释,我不知道该怎么问!

谢谢!

1 个答案:

答案 0 :(得分:0)

假设您保存名称的Dairy视图控制器为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
    }
}