微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义协议委托为零

如何解决自定义协议委托为零

我有一个奇怪的错误,我的委托为零并且不知道在哪里检查。也许其他人也有同样的问题。

我有这个类和协议:

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 的消息已打印).

来自扩展的委托方法从未被触发,因为委托为零。

我还在每个类的 deinit 中打印了一些消息,看看它是否以某种方式从内存中删除,但它们没有,只有在我从 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")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。