Created
November 1, 2016 13:34
-
-
Save owenzhao/1db515b158141e7c463afaf363491da6 to your computer and use it in GitHub Desktop.
UserDefaults bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in AppDelegate.swift | |
let TableViewControllerDidAppear = NSNotification.Name("TableViewController did Appear") | |
// in PreferencesViewController.swift | |
class PreferencesViewController: NSViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do view setup here. | |
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange), name: UserDefaults.didChangeNotification, object: UserDefaults.standard) | |
NotificationCenter.default.addObserver(self, selector: #selector(tableViewDidAppear(noti:)), name: TableViewControllerDidAppear, object: nil) | |
} | |
override func viewWillDisappear() { | |
super.viewWillDisappear() | |
NotificationCenter.default.removeObserver(self, name: UserDefaults.didChangeNotification, object: nil) | |
NotificationCenter.default.removeObserver(self, name: TableViewControllerDidAppear, object: nil) | |
} | |
weak var tableViewController:TableViewController? | |
func userDefaultsDidChange() { | |
guard let controller = tableViewController else { return } | |
controller.run() | |
} | |
func tableViewDidAppear(noti:Notification) { | |
if let controller = noti.object as? TableViewController { | |
tableViewController = controller | |
} | |
} | |
} | |
// in TableViewController.swift | |
class TableViewController: NSViewController, NSTableViewDelegate { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do view setup here. | |
run() | |
NotificationCenter.default.post(name: TableViewControllerDidAppear, object: self) | |
} | |
func run() { | |
// do things | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment