Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling delegate method through different classes in Swift

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)
    }
}
like image 529
Clinton Lam Avatar asked Nov 22 '25 22:11

Clinton Lam


1 Answers

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.

like image 101
WsCandy Avatar answered Nov 25 '25 12:11

WsCandy