Search code examples
swiftnsnotification

Adding NSNotification Observer using swift


I was using this example which explains the use of NSNotification.

In my case, I have a UIViewController in which I have a UITableView. To this tableview I am assigning a dataSource and delegate programatically by instatiating my UITableViewController. So far I have not declared any inits, and thus have been using the simple init() to initialize my UITableViewController. (This UITableViewController is not on the StoryBoard).

class foo: UIViewController{
      @IBOutlet weak var fooTable: UITableView!
      var fooTableViewController = MyTableViewController()

      override func viewDidLoad(){
             super.viewDidLoad()
             fooTable.delegate = fooTableViewController
             fooTable.dataSource = fooTableViewController
      }
}

class MyTableViewController: UITableViewController {
     override func viewDidLoad(){
           super.viewDidLoad()
           NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived", name: "TEST_NOTIFICATION", object: nil)
     }
}

If I try to add the observer in viewDidLoad() of the UIViewController, it does not work.

So my question is: Does using the NSNotification require the usage of init(coder aDecoder: NSCoder)? If so, then what is the correct way to initialize using this init in swift? How should I be instantiating MyTableViewController in my UIViewController instance foo?


Solution

  • viewDidLoad is only called when the view of a view controller is loaded - in the code you're showing you create a table view controller subclass, assign it as the datasource and delegate of another table view (confusing, as it will already be the datasource and delegate of its own table view), but never actually do anything with the table view controller's view.

    This means that viewDidLoad will not be called.

    You should probably be adding your table view controller's tableView as a subview and also adding it as a child view controller so that rotation and appearance events are forwarded properly.

    Note that the question and answer are nothing whatsoever to do with notification centers or Swift, but just about understanding the view controller lifecycle.

    If you want a separate object to act as a datasource and delegate for your table view, great idea, but don't use a UITableViewController subclass. Just create a plain object which conforms to the data source and/or delegate protocols.