[英]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.