You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Core Data编辑操作失效且应用启动时旧用户记录不显示问题求助

问题排查与修复方案

问题1:应用启动后历史存储记录不展示

  • 根因:viewDidLoad 生命周期方法仅完成了TableView的基础配置,没有调用Core Data数据拉取方法fetchPerople(),启动时数据源数组items默认是空值,只有新增用户触发拉取操作后才会加载所有历史数据。
  • 修复方法:在viewDidLoad方法末尾添加fetchPerople()调用,代码如下:
override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.register(UINib(nibName: String(describing: StundentCell.self), bundle: .main), forCellReuseIdentifier: String(describing: StundentCell.self))
    // 新增下面这行代码
    fetchPerople()
}

问题2:编辑人名功能失效

  • 根因:点击单元格弹出编辑弹窗的保存逻辑中,仅修改了局部字符串变量person的值,没有更新对应Core Data的Person模型对象的name属性,托管上下文context检测不到数据变更,保存操作没有实际效果。
  • 修复方法:编辑时持有对应的Person对象,保存时直接修改该对象的name属性,修正后的didSelectRowAt方法代码如下:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 持有当前点击的Person对象,而不是仅拿到name字符串
    let targetPerson = items[indexPath.row]
    let alertController = UIAlertController(title: "Edit Person", message: "Edit name", preferredStyle: .alert)
    alertController.addTextField()
    let alertField = alertController.textFields![0]
    alertField.text = targetPerson.name
    
    let saveBtn = UIAlertAction(title: "Save", style: .default) { (action) in
        guard let newName = alertController.textFields![0].text else { return }
        // 直接修改Core Data模型对象的属性
        targetPerson.name = newName
        do{
            try self.context.save()
        }
        catch{
            print(error)
        }
        self.fetchPerople()
    }
    alertController.addAction(saveBtn)
    self.present(alertController, animated: true, completion: nil)
}

其他优化建议

  • 你提供的代码中重复定义了两次ViewController的属性、viewDidLoad、方法扩展等内容,需要清理重复代码避免编译报错。
  • 方法名fetchPerople存在拼写错误,建议修正为fetchPeople符合命名规范。
  • 所有catch块建议添加错误打印逻辑,方便后续排查问题。

内容的提问来源于stack exchange,提问作者Faheem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:24:03