Swift 学习之 NotificationCenter

1、发布新通知:

NotificationCenter.default.post(name:  NSNotification.Name(rawValue: "MessageMainCount"), object: nil, userInfo: ["count":"\(count)"])

 2、接受新通知

NotificationCenter.default.addObserver(self, selector: #selector(self.changeBadgeValue(notification:)), name: NSNotification.Name(rawValue: "MessageMainCount"), object: nil)

 3、设置接受通知的监听方法

func changeBadgeValue(notification: Notification) -> Void {
        
        let name = notification.name
        let userInfo = notification.userInfo as! [String:Any]
        let userInfoDic = userInfo as NSDictionary
        
        if name == NSNotification.Name(rawValue: "MessageMainCount"){
 
            let badgeValue: String = userInfoDic.object(forKey: "count") as! String
           
            self.messageVC.parent?.tabBarItem.badgeValue = badgeValue
        }
}

 4、移除通知监听

deinit{
        NotificationCenter.default.removeObserver(self)
}

 

posted @ 2016-12-05 17:57  Now,OnMyWay  阅读(2251)  评论(0编辑  收藏  举报