ios - 更新 RealmSwift 中的对象?

标签 ios swift realm updates

我知道周围有很多类似的问题 - 我担心我的问题处于如此基本的水平,以至于我能找到的所有其他问题都要复杂得多,但似乎并不能完全回答这个问题。

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

要了解我的问题:对于应用程序的初学者,您有一个包含所有当前日记的 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/

相关文章:

ios - 如何在 iOS objective-c 中将 firebase 时间戳转换为日期?

json - 我需要创建一个带有嵌套 Json 的 TableView

Swift 中的类变量

database - Realm 如何查询数组大小大于 0 的项目?

ios - 查看方向变化

iphone - 浮点函数返回值

java - Android Realm Arraylist 和简单的 POJO

swift - Realm 在编写过程中如何处理错误?

ios - 实现另一个 @objc 协议(protocol)的 Swift 协议(protocol)

ios - 对于像 android CoordinatorLayout 这样的 iOS