微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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) 被释放了")
}

原文地址:https://www.jb51.cc/swift/321724.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐