Swift Delegate在展开Optional值时返回意外发现的nil

时间:2019-05-05 03:11:54

标签: ios swift delegates protocols

在协议中设置我的代理仍然失败。我尝试了其他帖子中建议的多种方法。我试图启动并运行我的协议+委托,但是无法解决为什么它继续抛出nil的问题。

强制展开,从文件中的各个位置调用委托,删除并添加Weak Var。

列表视图:

protocol MixPlayer : class {
    func playMix(message: String)
}


class IssueViewController: UIViewController {

    @IBOutlet weak var issueCollection: UICollectionView!
    @IBOutlet weak var issueImage: UIImageView!

    var viewController: ViewController?

    var collectionViewtitle: String?
    var mixImageName: String?

    var mixList: [[String: String]]!

    weak var mixDelegate: MixPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        issueCollection.dataSource = self
        issueCollection.delegate = self

    }

}
....

extension IssueViewController: UICollectionViewDelegate, UICollectionViewDataSource {

....

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if let url = mixList[indexPath.row]["url"] {
            mixDelegate?.playMix(message: url)
        }
    }   
}

视图控制器:

import UIKit

class ViewController: UIViewController  {
    @IBOutlet weak var mainContainer: UIView!
    @IBOutlet weak var playerEmbedView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondVC = IssueViewController()
        secondVC.mixDelegate = self

    }
}

extension ViewController: MixPlayer {
    func playMix(message: String) {
        print(message)
    }
}

任何尝试致电

mixDelegate?.playMix(message: url)

不成功。目前,我只是想记录基本的打印语句。

1 个答案:

答案 0 :(得分:0)

secondVC中的ViewController可能被释放。在您的ViewController中将其设为财产。

class ViewController: UIViewController  {
    @IBOutlet weak var mainContainer: UIView!
    @IBOutlet weak var playerEmbedView: UIView!

    lazy var secondVC: IssueViewController = {
        let secondVC = IssueViewController()
        secondVC.mixDelegate = self
        return secondVC
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    ... 
}

要知道您的类是否被释放,请添加带有打印语句的deinit。

deinit {
    print("Deallocated")
}