How do you share data between view controllers and other objects in Swift?

后端 未结 8 1149
长情又很酷
长情又很酷 2020-11-22 02:15

Say I have multiple view controllers in my Swift app and I want to be able to pass data between them. If I\'m several levels down in a view controller stack, how do I pass d

8条回答
  •  独厮守ぢ
    2020-11-22 03:12

    It depends when you want to get data.

    If you want to get data whenever you want, can use a singleton pattern. The pattern class is active during the app runtime. Here is an example of the singleton pattern.

    class AppSession: NSObject {
    
        static let shared = SessionManager()
        var username = "Duncan"
    }
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            print(AppSession.shared.username)
        }
    }
    

    If you want to get data after any action, can use NotificationCenter.

    extension Notification.Name {
        static let loggedOut = Notification.Name("loggedOut")
    }
    
    @IBAction func logoutAction(_ sender: Any) {
        NotificationCenter.default.post(name: .loggedOut, object: nil)
    }
    
    NotificationCenter.default.addObserver(forName: .loggedOut, object: nil, queue: OperationQueue.main) { (notify) in
        print("User logged out")
    }
    

提交回复
热议问题