[英]Custom Protocol delegate is nil
我有一个奇怪的错误,我的代表为零,不知道在哪里检查。 也许其他人也有同样的问题。
我有这个 class 和协议:
protocol NavigationProtocol: class {
func pushVC()
}
class LocalNotification: NSObject, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
weak var delegate: NavigationProtocol? {
didSet {
print("was set")
}
}
.........
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
self.delegate?.pushVC()
completionHandler()
}
在我的 VC 中
class FinalDecisionViewController: UIViewController {
var localNotification: LocalNotification!
override func viewDidLoad() {
super.viewDidLoad()
setupNotification()
}
private func setupNotification() {
localNotification = LocalNotification()
localNotification.delegate = self
localNotification.scheduleNotification(title: "Loan Approval", message: "Congratulations! Your loan has been approved", type: "Loan Approval")
}
extension FinalDecisionViewController: NavigationProtocol {
func pushVC() {
canMoveToNextVC = true
}
}
触发计划通知后,我单击它并调用didReceive
并且self.delegate?.pushVC()
以某种方式为零,即使已设置委托(已打印来自didSet
的消息)。
由于委托为 nil,因此从未触发扩展中的委托方法。
我还在每个 class 的deinit
中打印了一些消息,以查看它是否以某种方式从 memory 中删除,但它们不是,只有在我从 vc 堆栈中弹出它们之后。
添加
weak var delegate: NavigationProtocol? {
didSet {
print("was set")
notificationCenter.delegate = self
}
}
或者
localNotification = LocalNotification()
localNotification.delegate = self
localNotification.notificationCenter.delegate = localNotification
localNotification.scheduleNotification(title: "Loan Approval", message: "Congratulations! Your loan has been approved", type: "Loan Approval")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.