通知

来源:互联网 发布:职称计算机模拟软件 编辑:程序博客网 时间:2024/05/21 15:47

创建一个发通知的对象

import UIKit


class People: NSObject {


    var title ="title"

    

    overrideinit() {

        //发送通知

        NotificationCenter.default.post(name:Notification.Name(rawValue:"gameOverNotification"), object: title)

    }

    

}


//ViewController


import UIKit


class ViewController: UIViewController {


    overridefunc viewDidLoad() {

        super.viewDidLoad()

        

        //注册通知


        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.makeSomething(_:)), name:NSNotification.Name(rawValue:"gameOverNotification"), object: nil)


//创建People对象时会调用init方法发送通知,注意注册与发送通知名要一致

        _ =People()

        


    }

    

//接收到通知后执行的方法

    func makeSomething(_ title:Notification){

    

        let str = title.objectas! String

        print(str)

    }


//当视图消失时调用deinit方法移除通知

deinit {

        

        NotificationCenter.default.removeObserver(self)

    }



    overridefunc didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        

        

    }



}