14

In a ViewController, I'm trying to reload data in a TableView in another ViewController like so:

    (self.presentedViewController as! tableViewController).table.reloadData()

Where tableViewController is the class in the TableView's controller (It's not upper camel case, I know) and table is the TableView. Well, doing this yields "fatal error: unexpectedly found nil while unwrapping an Optional value" and I guess that makes sense since the "presentedViewController" hasn't been loaded yet. I also tried this:

    (self.navigationController!.viewControllers[self.navigationController!.viewControllers.count - 2] as! tableViewController).table.reloadData()

which yielded the same result (I made sure the tableViewController was under the current ViewController on the navigationController stack). I'm baffled about what I should do...I feel like it should be easier to refer to properties in different view controllers. I may be a little vague; if I am, tell me what you need to know!

user2252374
  • 153
  • 1
  • 6
  • I'm trying to understand why you would want to do this. View controllers should generally deal with their own properties and not tell other view controllers what to do. Maybe there's a better way to solve your problem? – Mike Taverne May 30 '15 at 00:58

1 Answers1

43

Xcode 9 • Swift 4

Create a Notification Name:

extension Notification.Name {
    static let reload = Notification.Name("reload")
}

You can post a notification

NotificationCenter.default.post(name: .reload, object: nil)

And add an observer at the view controller that you want to reload the data:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(reloadTableData), name: .reload, object: nil)
}

@objc func reloadTableData(_ notification: Notification) {
    tableView.reloadData()
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    But if I am not on that tableView means on another page or view controller,.. at that time NSNotificationCenter.defaultCenter() part will never happen bcoz its never loaded at that time ..then how can i handle it. – PRADIP KUMAR Dec 21 '16 at 07:56
  • @Leo, first off, thank you for a very helpful answer. Second, you obviously know more than me about Swift so I was wondering if you could explain what makes the version of Xcode relevant. Even the [Swift language page](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) doesn't reference the version of Xcode that's necessary to run Swift 3.1. – John R Perry Apr 18 '17 at 15:55