swift中通知NSNotificationCenter的使用

github学习地址:https://github.com/potato512/SYSwiftLearning

使用通知注意事项:

(1)接收通知前必须先移除掉通知,避免只发一次通知时,却出现两次或多次的响应事件;

(2)使用通知的类在被释放时,必须要移除通知

效果图:


代码示例:

func sendNotification()
{
        // 发送通知
        // 无参数
        // NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: nil,userInfo: nil)
        
        // 带参数
        let number = random() % 1000
        let numberString = ("\(number)" as String)
        let dict = ["number":numberString];
        NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: dict)
        
        // NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: self,userInfo: uderInfo)
}

func addNotification()
{
        // 接收通知
        
        // 先移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self,name: "ChangeBackgroundColor",object: nil)
        
        // 无参数
        // NSNotificationCenter.defaultCenter().addobserver(self,selector: Selector("notificationAction"),object: nil)
        
        // 带参数
        NSNotificationCenter.defaultCenter().addobserver(self,selector: Selector("notificationAction:"),object: nil)
}

// func notificationAction() // 无参数
func notificationAction(notification:NSNotification) // 带参数
{
        // 通知响应方法
        let color = UIColor.init(red: (((CGFloat)(random() % 256) / 255.0)),green: (((CGFloat)(random() % 256) / 255.0)),blue: (((CGFloat)(random() % 256) / 255.0)),alpha: 1.0)
        self.view.backgroundColor = color
        
        // 参数
        let name = notification.name
        let dict = notification.object
        let numberText = dict?.valueForKey("number") as! String
        let text = "通知名称:\(name),传值:\(numberText)"
        label.text = text
}

deinit
{
        // 移除通知
        NSNotificationCenter.defaultCenter() .removeObserver(self)
        
        print("\(self) 被释放了")
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...