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

Swift iOS开发:Realm增删改后TableView无法刷新求助

问题诊断与修复方案

你遇到的问题核心是编辑/删除流程中,负责刷新TableView的委托(delegate)没有正确关联到HomeViewController,导致数据变更后无法触发loadData()方法刷新界面。以下是具体修复步骤:

1. 修复删除流程的委托关联

在HomeViewController的didSelectRowAt方法中,给跳转到的DisplayDataViewController设置delegate:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    
    let displayVc = storyboard?.instantiateViewController(identifier: "displayData") as! DisplayDataViewController
    displayVc.index1 = indexPath.row
    displayVc.viewDetails = taskView![indexPath.row]
    // 新增此行:将HomeViewController设为DisplayData的委托
    displayVc.delegate = self
    navigationController?.pushViewController(displayVc, animated: true)
}

这样删除按钮点击后,delegate?.loadData()就能正确调用HomeViewController的刷新方法。

2. 修复编辑流程的委托关联

在DisplayDataViewController的EditButtonPressed方法中,给跳转到的AddNotesViewController传递委托:

@IBAction func EditButtonPressed(_ sender: UIButton) {
    let editVc = storyboard?.instantiateViewController(identifier: "goToAdd") as! AddNotesViewController
    editVc.index2 = index1
    editVc.EditView = viewDetails
    editVc.flagEdit = 1
    // 新增此行:把HomeViewController的委托传递给编辑页面
    editVc.delegate = self.delegate
    navigationController?.pushViewController(editVc, animated: true)
}

这样编辑完成后,AddNotesViewController的delegate?.loadData()就能触发HomeViewController刷新TableView。

额外优化建议(可选)

Realm的Results类型是自动更新的集合,你可以通过监听Realm通知来实现自动刷新,无需手动调用loadData():
在HomeViewController的viewDidLoad中添加通知监听:

override func viewDidLoad() {
    super.viewDidLoad()
    
    tableViewField.delegate = self
    tableViewField.dataSource = self
    loadData()
    
    // 监听Realm数据变更通知
    NotificationCenter.default.addObserver(self, selector: #selector(realmDataChanged), name: Notification.Name.RealmCollectionDidChange, object: taskView)
}

@objc func realmDataChanged() {
    tableViewField.reloadData()
}

// 页面销毁时移除监听
deinit {
    NotificationCenter.default.removeObserver(self)
}

这种方式更符合Realm的特性,后续所有CRUD操作后TableView都会自动刷新,不需要依赖委托调用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:02:53