【问题标题】:Passing Index Path through Navigation Controller - Update CoreData Record通过导航控制器传递索引路径 - 更新 CoreData 记录
【发布时间】:2021-05-17 16:06:54
【问题描述】:

我正在尝试创建一个日记应用程序,并有一个包含条目列表的表格视图。添加新按钮可添加新记录,单击表中的行可编辑记录。 Add new 和 Edit 都将您带到一个不同的视图控制器,该控制器都设置在 Navigation 控制器中。

我已经完成了大部分工作,除了更新记录时遇到问题。编辑时,它会添加一条新记录而不是更新旧记录(使用当前条目数据)。在转移到另一个 vc 之前,我使用了一个对话框。

查看代码看起来是因为我没有通过索引路径。有谁知道我如何做到这一点?我当前的代码如下。有任何问题请告诉我。

添加新记录

@IBAction func addNew(_ sender: Any) {
        let newEntry = DiaryEntry(context: self.context)
        newEntry.entry = self.entryEntry.text //The Main Entry
        newEntry.date = Date() //The Date (Auto)
        newEntry.rating = Int16(self.ratingInt) //The Rating
        newEntry.entryName = self.entryName.text //The Entry Name
        
        do{
            try self.context.save()
            dismiss(animated: true, completion: nil)
            //print("Saved correctly")
        }catch{
            print(error)
        }
        self.fetchData()
    }

更新当前记录

@IBAction func updateRecord(_ sender: Any) {
        let newEntry = DiaryEntry(context: self.context)
        newEntry.entry = self.entryEntry.text //The Main Entry
        newEntry.date = Date() //The Date (Auto)
        newEntry.rating = Int16(self.ratingInt) //The Rating
        newEntry.entryName = self.entryName.text //The Entry Name
        do{
            try self.context.save()
            dismiss(animated: true, completion: nil)
            //print("Saved correctly")
        }catch{
            print(error)
        }
        self.fetchData()
    }

据我了解,我认为问题出在 newEntry 上下文部分。不过我有点失落。

这就是我将它放在警报框中时的代码(并且有效)

let entry = self.items![indexPath.row]
    let alert = UIAlertController(title: "Edit Entry", message: "Edit an entry to your Diary", preferredStyle: .alert)
    alert.addTextField()
    let textfield = alert.textFields![0]
    textfield.text = entry.entry
    let saveBtn = UIAlertAction(title: "Save", style: .default) { (action) in
        entry.entry = textfield.text
        do {
            try self.context.save()
        }catch{
            print(error)
        }
        self.fetchData()
    }

    let cancelBtn = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    alert.addAction(saveBtn)
    alert.addAction(cancelBtn)
    self.present(alert, animated: true, completion: nil)

我知道这很简单,但我无法解决。

谢谢

【问题讨论】:

    标签: ios swift xcode uiviewcontroller uinavigationcontroller


    【解决方案1】:

    在推送版本 VC 之前,您可以保存要编辑的项目的 indexPath.row 并在 updateRecord 中放置您之前拥有的代码而不是 newRecord 代码。

    【讨论】:

    • 当您说“保存 indexPath.row”时,您的意思是将其存储在变量中吗?还是保存到核心数据?
    • 在导航控制器的实例变量中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 2016-07-25
    • 2015-12-04
    • 1970-01-01
    • 2016-03-26
    • 2015-02-10
    相关资源
    最近更新 更多