如何正确调用协议功能?

时间:2018-01-29 11:13:16

标签: ios swift delegates protocols

因此,我需要为我的应用从服务器收到的每个通知创建通知处理程序类。为此目的,我像下面一样上课:

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

   }


}

以下是我在视图控制器上调用它的方式:

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 。难道我做错了什么?

1 个答案:

答案 0 :(得分:1)

使用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。