I am fetching JSON menu and once the JSON returned, I would like to run menuReady() to update content of the table within SomeTableViewController class. But the following code doesn't seems to work.
AIM: Run menuReady() to update content once JSON returned.
PROBLEM: menuReady() is never fired.
SomeTableViewController.swift
class SomeTableViewController: UITableViewController, MenuModelDelegate {
override func viewDidLoad() {
menuModel.delegate = self
}
func menuReady() {
// This is NOT fired.
print("SomeViewController.menuReady()")
}
}
MenuModel.swift
protocol MenuModelDelegate : class {
func menuReady()
}
class MenuModel: NSObject {
var delegate:MenuModelDelegate?
func getMenu(data: JSON) {
// This is fired.
print("MenuModel.getMenu()")
delegate?.menuReady()
}
}
Call from AnotherViewController when button tapped
AnotherViewController.swift
class AnotherViewController : UIViewController {
func buttonTapped(sender: UIButton!) {
// This function is fired.
// jsonData is some json data returned from http request
let menuModel = MenuModel()
menuModel.getMenu(data: jsonData)
}
}
A delegate method is designed to work in a "one on one" relationship what you're trying to achieve here won't work as you have multiple different instances of MenuModel in different places. You should try initialising MenuModel as a property of SomeTableViewController and use it like the following:
class SomeTableViewController: UITableViewController, MenuModelDelegate {
private let menuModel: MenuModel = MenuModel()
override func viewDidLoad() {
self.menuModel.delegate = self
self.menuModel.getMenu(data: jsonData)
}
func menuReady() {
print("SomeTableViewController.menuReady()")
}
}
If you're looking for a solution that will update multiple view controllers then a better solution would be to read up on NotificationCenter. Using notifications you can add observers to multiple view controllers/classes and simply get your MenuModel to post a notification.
https://developer.apple.com/documentation/foundation/notificationcenter
I hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With