iOS 通知中心 发布-订阅者模式 NotificationCenter

写了几天iOS已经轻车熟路了~~~~~~


//
//  ViewController.swift
//  Xcodetest
//
//  Created by Wirhui on 2018/12/26.
//  Copyright © 2018 Wirhui. All rights reserved.
//

import UIKit
import  NotificationCenter

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    //单击按钮发送调用的数据
    @IBAction func NotifyTest(_ sender: Any) {
        /// 发送简单数据
//        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "Hello"), object: "Hello 2017")
        
        /// 发送额外数据
        let info = ["name":"Eric","age":21] as [String : Any]
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "Hello"), object: "GoodBye 2016", userInfo: info)

        
    }
    
    //设置监听Hello
    override func viewDidAppear(_ animated: Bool) {
         print("页面出现")
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name.init("Hello"), object: nil)
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        print("页面消失")
    }
    
    @objc func notificationAction(info:NSNotification)  {
        print("监听到消息\(info)")
    }
    
    //移除监听
    deinit {
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }


}




你可能感兴趣的:(iOS 通知中心 发布-订阅者模式 NotificationCenter)