iOS

Swift4.0 通知的使用

2018-01-01  本文已影响768人  BrumeLoong

通知一般在mode与View需要交流(传递数据)时使用,或者也可以用于多线程的消息传递,也可是VC与VC或者VC内部的信息传递,最常用的场景是页面值的回传。
下面就介绍一下使用方法

创建通知中心
设置监听方法
设置通知的名字
        NotificationCenter.default.addObserver(self, selector: #selector(test), name: NSNotification.Name(rawValue:"isTest"), object: nil)

实现通知监听方法
@objc func test(nofi : Notification){
        let str = nofi.userInfo!["post"]
        print(String(describing: str!) + "this notifi")
    }

点击发送通知进行
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        NotificationCenter.default.post(name: NSNotification.Name("isTest"), object: self, userInfo: ["post":"NewTest"])
    }

最后要记得移除通知
    deinit {
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }

通知的一般使用流程就是这样了,还有其他的使用流程就自己去尝试吧

上一篇下一篇

猜你喜欢

热点阅读