Swift中使用NSNotificationCenter注意点

Home / iOS MrLee 2016-3-22 3791

我也是菜鸟,现在需要用到NSNotificationCenter,这个就类似Android里面的广播,iOS中叫观察者Observer。简单写了一个例子成功运行。先看例子。
let Center = NSNotificationCenter.defaultCenter()
Center.addObserver(self, selector: "Command:", name: className(), object: nil)
//回调方法
func Command(notification:NSNotification){
     print("Command->notification")
 }
//发送广播
Center.postNotificationName(className(), object: nil)
//快速取当前的类名
 func className() -> String!{
     return String(classForCoder)
 }
   

这个是在ViewController中完成的,但是我后来放到普通的NSObject类中,执行这些代码,Command函数其实是不会触发的。所以这个只有在VC中使用。我现在也没有文档,也不敢100%确定!
最后,在deinit方法里面移除广播观察者!
 deinit{
     Center.removeObserver(self)
     print("\(self.classForCoder) deinit")
 }

最后来看下,怎么传参数,以上面为例!先发送广播
Center.postNotificationName(className(), object: ["name":"ithtw","pwd":"123"])

然后是接收
func Command(notification:NSNotification){
     let params = notification.object as! [String:AnyObject]//健值对 方便取值
     print("广播接收的值:\(params["name"] as! String) 和 \(params["pwd"] as! String)")
}

 

本文链接:https://www.it72.com/8341.htm

推荐阅读
最新回复 (0)
返回