ios - 委托(delegate)给另一个 View Controller 不起作用

标签 ios swift swift-protocols delegation

我的委托(delegate)发件人类:

import UIKit

protocol tapDelgation:class {
    func tapConfirmed(message:String)
}

class ViewController: UIViewController {
    weak var delegate:tapDelgation?

    @IBAction func deligateSenderAction(_ sender: Any) {
        var data = "hello world"
        print(data)
        self.delegate?.tapConfirmed(message: data)
    }
}

我的接收者类:

import UIKit

class NextViewController: UIViewController {
    weak var vc:ViewController? =  ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        vc?.delegate = self
    }
}

extension  NextViewController : tapDelgation {
    func tapConfirmed(message: String) {
        print(message)
    }
}

预期结果:发送方 vc 上的按钮被按下,接收方 vc 将弹出一个控制台打印。但徒劳无功,什么也没有发生。有谁知道为什么会这样?如果不可能,那为什么?

最佳答案

在我看来这像是一个内存管理问题。

第一个问题:使用像 ViewController() 这样的默认初始化器创建 View Controller 几乎从来都不是正确的做法。因为它不会有任何 View 内容。

您没有解释如何创建和显示您的 NextViewController 和您的 ViewController

看起来NextViewControllerViewController的引用很弱,ViewController的delegate point也很弱(delegate references should almost always虚弱。)

这一行:

weak var vc:ViewController? =  ViewController()

将导致 NextViewController 创建一个不属于任何人的 ViewController 实例,因此它将立即被释放并且 vc变量将恢复为零。当您到达 NextViewController 的 viewDidLoad 时,vc 将为 nil,因此 vc?.delegate = self 行中的可选绑定(bind)不会做任何事情。

NextViewControllervc 变量几乎肯定是一个强引用,而不是弱引用,但您没有显示 ViewController 是如何获取的显示在屏幕上,因此不清楚您要做什么。

关于ios - 委托(delegate)给另一个 View Controller 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238267/

相关文章:

swift - 为什么我可以使用继承协议(protocol)的结构来设置协议(protocol)的只读属性?

ios - MFMailComposeViewController 不会关闭

swift - 如何将 DispatchQueue 去抖动转换为 Swift 并发任务?

ios - 将数据从 View Controller 传递到 Cocos2D 场景

objective-c - 在 swift 框架中使用 j2objc(不是静态库)

ios - UIWebView FinishLoad/检测问题

属性符合协议(protocol)的 Swift 协议(protocol)扩展

ios - 如何使不同的类遵循具有不同功能的相同协议(protocol)?

ios - 分析 iPad 项目的内存泄漏

iOS - 具有平移缩放手势的开源图像幻灯片库