在协议(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/