gpt4 book ai didi

swift - 从类外的模型文件激活类上的 segue?实例成员不能用于类型

转载 作者:行者123 更新时间:2023-11-30 10:49:35 27 4
gpt4 key购买 nike

我的应用程序有一个模型文件,我可以在其中检查我的 API。如果网络检查因特定代码( token 无效)而失败,我希望应用程序返回到登录页面。

我的挑战是 API 调用存储在我的模型文件中,而不是 View Controller 类中。

有没有办法在实际类之外激活模型文件中的segue?

我尝试在 TabBarController 类上创建注销功能,并在我的模型中使用它来激活转场:

class InitialTabBarController: UITabBarController {
...
func logoutFresh(){
performSegue(withIdentifier: "logoutFresh", sender: self)
}

}

然后在我的模型中添加:

func pullAPIData(){
...
if httpResponse == 403 {
InitialTabBarController.logoutFresh()
}
}

我在另一个 View Controller 类(tabBarController 中的 viewController 之一)中调用 pullAPIData() 函数

但是,这会产生一个错误:实例成员“logoutFresh”不能用于类型“InitialTabBarController”;您是否打算使用这种类型的值?

有没有办法检查InitialTabBarController是否处于事件状态,然后让它从模型文件启动segue?或者有更好的方法来处理这个问题?

最佳答案

基本上,iOS 使用委托(delegate)模式或完成处理程序模式来解决此类场景;

在委托(delegate)模式中,您在模型类中设置一个指向 View Controller 的弱变量。这样,一旦网络调用完成,您就可以使用此委托(delegate)来调用 View Controller 中的函数

在完成处理程序模式中,您发送一个代码块,该代码块应在 api 调用完成后执行,如下所示:

func pullAPIData(completion: () -> Void){
//do your stuff
completion()
}

您可以引用以下帖子来更好地了解委托(delegate)和完成处理程序: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef https://medium.com/@nimjea/completion-handler-in-swift-4-2-671f12d33178

关于swift - 从类外的模型文件激活类上的 segue?实例成员不能用于类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54934380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com