Reputation: 1678
In my HomeViewController viewDidLoad method I have an observer that looks out for a new notification. When observed it segues to a SecondTableVC. I have an observer in the second VC looking for the same notification, but the second observer isn't seeing the notification and calling the method. Thanks in advance to anyone who can explain what I'm missing here? I removed the observer in both viewDidLoad and in the segue method, but it doesn't fix it.
var childVC: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
childVC = self.storyboard?.instantiateViewControllerWithIdentifier("WordListsTableViewController")
// check for new notification - if there is segue to the SecondTableVC
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.showChildVC), name: "NotificationActionPressed", object: nil) // Segue works fine.
}
func showChildVC() {
self.view.addSubview(childVC.view)
}
In SecondTableVC
override func viewDidLoad() {
super.viewDidLoad()
// check for new notification - if there is
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SecondTableVC.newNotif), name: "NotificationActionPressed", object: nil)
}
func newNotif() {
print("new notif") // THIS METHOD IS NOT GETTING CALLED
}
Upvotes: 1
Views: 1749
Reputation: 680
Kind of piggybacking off of the answer from Phillip: If it is absolutely necessary that the second view controller listen to the NSNotification event, then the second view controller can be instantiated from the storyboard and held in memory by the first view controller until it needs to be displayed. In this case, the second view controller should subscribe to the notification event upon initialization.
Upvotes: 1
Reputation: 31016
Your segue causes the second view controller to be created. If the segue is triggered by a notification, then the SecondTableVC
's viewDidLoad
hasn't happened when the notification fires.
The second controller's not receiving the notification because it not only hasn't registered by that time, but doesn't actually exist.
Upvotes: 0