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

标签 ios swift delegates protocols

在协议(protocol)中设置我的委托(delegate)继续抛出 nil。我尝试了其他帖子中建议的多种方法。我正在尝试启动并运行我的协议(protocol) + 委托(delegate),但是无法解决它继续抛出 nil 的原因。

强制解包,从文件中的不同位置调用委托(delegate),删除和添加 Weak Var。

ListView :

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)
        }
    }   
}

View Controller :

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)

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

最佳答案

可能是 ViewController 中的 secondVC 被释放了。将其设为 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")
}

关于ios - Swift Delegate 在展开 Optional 值时返回意外发现的 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55988522/

相关文章:

ios - 在iOS上使用带有参数的Xcode运行Shell脚本

ios - 当用户终止应用程序时重新连接蓝牙设备

swift - 检查字符串的日期格式是否符合要求的格式

ios - 在后台连续运行应用程序。 iOS swift

swift - UITextField 的 leftView 属性问题

ios - 无法从委托(delegate)方法中关闭 FBfriendPickerViewController

ios - 字符串转字典(二维码字符串取值)

ios - Swift:在单 View 应用程序中设置游戏场景

swift - 如何在 swift 中使协议(protocol)方法可选?

ios - 如何在两个单独的 View Controller 上跟踪数组的元素?