通过Swift中的不同类调用委托方法 [英] Calling delegate method through different classes in Swift

查看:140
本文介绍了通过Swift中的不同类调用委托方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取JSON菜单,一旦JSON返回,我想运行menuReady()来更新SomeTableViewController类中的表内容。但是以下代码似乎无效。

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:一旦返回JSON,运行 menuReady()更新内容。

AIM: Run menuReady() to update content once JSON returned.

问题: menuReady()不会被触发。

SomeTableViewController.swift

SomeTableViewController.swift

class SomeTableViewController: UITableViewController, MenuModelDelegate {
    override func viewDidLoad() {
        menuModel.delegate = self
    }
    func menuReady() {
        // This is NOT fired.
        print("SomeViewController.menuReady()")
    }
}

MenuModel.swift

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()
    }
}

在点击按钮时从AnotherViewController调用

Call from AnotherViewController when button tapped

AnotherViewController.swift

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)
    }
}


推荐答案

委托方法旨在一对一地工作关系,因为您在不同的地方有多个不同的 MenuModel 实例,所以您在这里想要实现的目标将无法正常工作。您应该尝试将 MenuModel 初始化为 SomeTableViewController 的属性,并按如下所示使用它:

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()")
    }
}

重新寻找一种可以更新多个视图控制器的解决方案,那么更好的解决方案是在 NotificationCenter 上阅读。使用通知,您可以将观察者添加到多个视图控制器/类中,并只需获取您的 MenuModel 即可发布通知。

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

我希望能帮上忙。

这篇关于通过Swift中的不同类调用委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆