swift中通知NSNotificationCenter的使用

swift中通知NSNotificationCenter的使用,第1张

概述github学习地址:https://github.com/potato512/SYSwiftLearning 使用通知注意事项: (1)接收通知前必须先移除掉通知,避免只发一次通知时,却出现两次或多次的响应事件; (2)使用通知的类在被释放时,必须要移除通知; 效果图: 代码示例: func sendNotification(){ // 发送通知 // 无参数

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

以上是内存溢出为你收集整理的swift中通知NSNotificationCenter的使用全部内容,希望文章能够帮你解决swift中通知NSNotificationCenter的使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1063137.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存