[英]Swift Delegate returns unexpectedly found nil while unwrapping an Optional value
Setting up my delegate within the protocol continues to throw nil. 在协议中设置我的委托继续抛出零。 I have attempted numerous approaches suggested in other posts. 我尝试过其他帖子中提出的众多方法。 I am attempting to get my protocol + delegate up and running, however, unable to solve why it continues to throw nil. 我试图让我的协议+委托启动并运行,然而,无法解决为什么它继续抛出零。
Force unwrapping, calling the delegate from various locations in the file, removing & adding Weak Var. 强制解包,从文件中的各个位置调用委托,删除并添加Weak Var。
List View: 列表显示:
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)
}
}
Any attempt at calling 任何打电话的尝试
mixDelegate?.playMix(message: url)
Is unsuccessful. 不成功。 Currently I'm just trying to log basic print statements. 目前我只是想记录基本的打印语句。
Probably your secondVC
inside the ViewController
gets deallocated. 可能你的ViewController
的secondVC
被解除分配。 Make that a property in your 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()
}
...
}
To know if your class gets deallocated, add a deinit with a print statement on it. 要知道您的类是否已取消分配,请在其上添加带有print语句的deinit。
deinit {
print("Deallocated")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.