委托/协议将数据从一个视图控制器传递到另一个视图控制器

时间:2018-01-23 14:17:22

标签: ios swift delegates protocols extension-methods

尝试将数据从一个视图控制器MainScreenVC传递到具有协议和扩展名的另一个RatesVC,但这不起作用,应用程序每次都崩溃。我清楚地看到第二个VC上的代码存在问题(因为打印在第一个VC上操作后显示正确的数据)但不确定错误在哪里。

StoryBoard and 1st VC Example Second VC

第一视图控制器

import UIKit

protocol transferNameOfCurrency {
    func currencySelected(nameOfCurrency: String)
}

class MainScreenVC: UIViewController {

    var transferCurrencyDelegate: transferNameOfCurrency?
    var nameOfTheCurrency: String?

    @IBAction func updateRates(_ sender: Any) {
        nameOfTheCurrency = "EUR"
        transferCurrencyDelegate?.currencySelected(nameOfCurrency: 
nameOfTheCurrency)
        print(nameOfTheCurrency)

    }
}

第二个ViewController

import UIKit

class RatesVC: UIViewController {
    var currencySelected: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let push = self.storyboard?.instantiateViewController(withIdentifier: "MainScreenVC") as? MainScreenVC
        {
            push.transferCurrencyDelegate = self
        }

         // Do any additional setup after loading the view.
    }
}

extension RatesVC: transferNameOfCurrency {
    func currencySelected(nameOfCurrency: String) {
       currencySelected = nameOfCurrency
       print(currencySelected)
    }

}

1 个答案:

答案 0 :(得分:3)

最明显的问题在于:

if let push = self.storyboard?.instantiateViewController(withIdentifier: "MainScreenVC") as? MainScreenVC {
    push.transferCurrencyDelegate = self
}

你必须意识到instantiateViewController创建了一个新的视图控制器 - 它不是对屏幕上显示的视图控制器的引用。在该代码中,您刚刚创建了一个全新的视图控制器,然后将其委托设置为self,但除此之外别无其他。

在不知道上下文的情况下,很难提出任何建议 - prepare(for:) segue可能是您想要设置委托的地方。无论如何,问题是你必须获得对屏幕上显示的控制器的引用,该引用应该是对这些事件的反应。

此外,从内存管理方面来说,您应该考虑将delegate属性设置为weak以防止内存泄漏。

修改

因此,在看到您在link提供的最小工作示例后,我想我可以提供有关如何将该字符串添加到SecondVC的解决方案。

您的第一个带注释的视图控制器:

import UIKit

class ViewController: UIViewController {

    var newLine: String = "EUR"

    @IBAction func push(_ sender: Any) {
        // here the secondVC does not exist yet, calling delegate.transferWord() here would have no sense
        // performSegue will create that secondVC, but now it does not exist, nor it is set up as the delegate
        self.performSegue(withIdentifier: "ViewController", sender: navigationController)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondVC, segue.identifier == "ViewController" {
            // at this moment secondVC did not load its view yet, trying to access it would cause crash
            // because transferWord tries to set label.text directly, we need to make sure that label
            // is already set (for experiment you can try comment out next line)
            secondVC.loadViewIfNeeded()
            // but here secondVC exist, so lets call transferWord on it
            secondVC.transferWord(word: newLine)
        }
    }
}

此处不需要代表,因为ViewController是将SecondVC推送到导航控制器的人 - 这意味着您可以直接在prepare(for:)中访问它,如您所见上方。

现在SecondVC非常简单(我省略了不必要的代码):

import UIKit

class SecondVC: UIViewController {

    @IBOutlet weak var label: UILabel!

    func transferWord(word: String) {
        label.text = word
    }
}

故事板可以保持原样。