swift4--使用通知中心监听和处理程序退出事件

//使用通知中心,实现监听和处理程序退出事件的功能
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
//        获得一个应用实例,作用是提供程序运用期间的控制和协作,每个程序必须有,且仅有一个应用实例
        let app = UIApplication.shared
//        通知中心是基础框架的子系统,它向所有监听退出事件的对象广播消息
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.doSomething(_:)), name: .UIApplicationWillResignActive, object: app)
        
    }
//    创建一个方法,使程序退出前保存用户数据
    @objc func doSomething(_ sender:AnyObject){
        print("Saving data before exit.")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_41735943/article/details/81232789