gpt4 book ai didi

ios - 如何正确调用协议(protocol)函数?

转载 作者:行者123 更新时间:2023-11-28 15:05:39 25 4
gpt4 key购买 nike

因此,我需要为我的应用从服务器收到的每个通知创建通知处理程序类。为此,我制作了如下类:

protocol NotificationHandlerDelegate: class {
func receiveNotification(content: Any)
}

class NotificationHandler{

var delegate : NotificationHandlerDelegate!

func handleTransactionNotif(content: Any, rootVC: UIViewController){

delegate?.receiveNotification(content: content)
((rootVC as! UINavigationController).viewControllers[0] as! UITabBarController).selectedIndex = 3

}


}

下面是我在 View Controller 上调用它的方式:

class TransactionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TransactionsCellDelegate, NotificationHandlerDelegate{

override func viewWillAppear(_ animated: Bool) {
let nh = NotificationHandler()
nh.delegate = self

self.navigationController?.navigationBar.isHidden = true
}


func receiveNotification(content: Any) {
print("called: \(content)")
let contentJSON = JSON(content)
goToScreenAccording(to: "\(contentJSON["status"])", selectedData: content as! [String: Any])
}

}

问题是当我收到通知时,receiveNotification 没有被调用。难道我做错了什么?

最佳答案

将 NotificationHandler 用作单例,因此您可以引用相同的实例:

class NotificationHandler {

weak var delegate: NotificationHandlerDelegate?

static let shared = NotificationHandler()

private init(){}

func handleTransactionNotif(content: Any, rootVC: UIViewController){

delegate?.receiveNotification(content: content)
((rootVC as! UINavigationController).viewControllers[0] as! UITabBarController).selectedIndex = 3

}
}

class TransactionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TransactionsCellDelegate, NotificationHandlerDelegate{

override func viewWillAppear(_ animated: Bool) {
let nh = NotificationHandler.shared
nh.delegate = self
self.navigationController?.navigationBar.isHidden = true
}
//...
}

并且记得在 AppDelegate 中也使用 NotificationHandler.shared。

关于ios - 如何正确调用协议(protocol)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com