Swift 学习之 NotificationCenter

本文详细介绍了如何在Swift中使用通知中心 NotificationCenter 进行消息传递。包括发布新通知、接收新通知、设置监听方法以及移除通知监听。通过具体代码示例展示了通知的发送与接收流程,帮助开发者理解通知中心在iOS应用中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
}

 

转载于:https://www.cnblogs.com/yxtBlogs/p/6134887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值