【问题标题】:Update objects in RealmSwift?在 RealmSwift 中更新对象?
【发布时间】:2018-11-09 09:15:20
【问题描述】:

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

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

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

在这里,当单击名为“日记名称”的 tableViewCell 时,您会输入一个简单的 viewController,其中包含一个文本字段(保存您当前的日记名称)和一个按钮,该按钮将弹出您并将日记名称更改为新的输入文本域。

这是我目前在这个“保存按钮”上的代码:

@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)
}

对不起,解释太长了,我不知道该怎么问!

谢谢!

【问题讨论】:

  • 请不要附图片,代码是正确的。
  • 打开包装 :) 点击红色圆圈,xcode 会建议你 :)
  • 强制展开使警告再次静音,但应用程序仍然崩溃。抱歉,我再把照片拍下来。
  • 请提供代码,如果可能的话,应用程序崩溃时的错误消息是什么
  • 好吧,当我像这样强制展开时:'realm.add(newDiaryName!)' 和当我这样做时:'let newDiaryName = diary!',我得到错误'线程 1 : 信号 SIGABRT'

标签: ios swift realm updates


【解决方案1】:

假设您保存名称的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
    }
}

【讨论】:

  • 嘿!我实际上是在推动它——但概念是一样的。我正在使用版本 1 - 我已经在这样做了。问题是,当我尝试访问我创建的新变量时,我收到错误:“可选类型的值'日记?'必须解包为“日记”类型的值“如果您愿意,我可以发布显示此错误的整个班级的照片?
  • 我贴了一张照片,展示了我尝试时发生的事情,你在版本 1 中也说过:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多