swift - 如何使用委托(delegate)模式将对象传输到另一个 VC?

标签 swift xcode delegates

我有一个应用程序,其中包含有关酒吧的信息。 listViewController 将每个 Bar 对象保存在单元格中(姓名、地址、电话等)。

当我按下单元格时,我移动到显示数据的 infoViewController,但由于某种原因它不起作用

这是TableView中的代码-

    func tableView(_ tableView: UITableView, didSelectRowAt 
    indexPath: IndexPath) {
    let barSelected = bars[indexPath.row]

      let infoVC = storyboard?.instantiateViewController(withIdentifier: "infoViewController") as! InfoViewController

    chooseBarDelegate?.chooseBar(barChosen: barSelected)
    present(infoVC, animated: true, completion: nil)

该类符合我创建的协议(protocol) -

导入基础

   protocol barInfoDelegate {
   func chooseBar(barChosen:Bar)
    }

我还创建了一个委托(delegate)实例 -

var chooseBarDelegate:barInfoDelegate?

在detailViewController中我创建了一个带有可选对象的var -

var infoBar:Bar?

并添加了扩展 -

extension InfoViewController: barInfoDelegate {
    func chooseBar(barChosen: Bar) {
        infoBar = barChosen
    }   
}

我还在 infoViewController 中将委托(delegate)设置为 self

    listViewController.chooseBarDelegate? = self

应用程序不会崩溃,但信息不会传递。 当我使用打印对象检查调试器时,我可以看到“barSelected”确实包含一个对象,但 infoBar 为零。

我做错了什么?

谢谢!

最佳答案

根本没有委托(delegate)的理由。删除 InfoViewController 上的协议(protocol)、chooseBarDelegate 属性和 barInfoDelegate 扩展。您唯一需要保留的是 InfoViewControllervar infoBar:Bar? 属性。

然后替换这一行:

chooseBarDelegate?.chooseBar(barChosen: barSelected)

与:

infoVC.infoBar = barSelected

关于swift - 如何使用委托(delegate)模式将对象传输到另一个 VC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774009/

相关文章:

xcode - 如何删除 Xcode 中的文件引用?

ios - itunes连接上传失败的xcode 9

c# - 如何在 C# 中实现线程安全的无错误事件处理程序?

ios - 将数组中的图像嵌入到 Collection View 的单元格中

swift - 了解 AppDelegate 中的保留计数

class - Apple Swift - 在 arc4random_uniform 中放置一个变量

c# - 为什么委托(delegate)实例不总是被缓存?

ios - 由于某些 Swift 版本问题,无法构建模块 XCTest?

ios - IOS 构建中的重复符号

objective-c - Objective-C : How to release delegates in this situation