let viewControllers: [UIViewController] = self.navigationController!.viewControllers
for VC in viewControllers {
if (VC.isKind(of: HomeViewController.self)) {
bScreen = true
self.navigationController?.popToViewController(VC, animated: true)
}
}
if bScreen == false {
let homeVC = HomeViewController()
self.navigationController?.pushViewController(homeVC, animated: false)
}
我循环浏览导航控制器阵列以移动到HomeViewController.above代码工作正常。有些时候我正在崩溃,因为“致命错误:在解开一个可选值时意外发现了nil。”我知道这次崩溃的原因。请告诉我。帮助我如何检查视图控制器对象的nil值。任何帮助将不胜感激。谢谢提前
答案 0 :(得分:1)
使用此代码。这对你有帮助。
Angularjs
答案 1 :(得分:1)
- Swift 3 -
for vc in (self.navigationController?.viewControllers)! {
if vc is HomeViewController {
_ = self.navigationController?.popToViewController(vc, animated: true)
}
}
答案 2 :(得分:1)
let getCurrentVCIndex = self.navigationController?.viewControllers.indexOf({ (viewController) -> Bool in
if let _ = viewController as? HomeViewController {
return true
}
return false
})
if getCurrentVCIndex
{
let HomeVC = self.navigationController?.viewControllers[getCurrentVCIndex!] as! HomeViewController
self.navigationController?.popToViewController(HomeVC, animated: true)
}
else
{
// use push
}
或使用
if let HomeVC = self.navigationController?.viewControllers.filter({$0 is HomeViewController}).first
{
self.navigationController?.popToViewController(HomeVC!, animated: true)
}else
{
// use push
}
答案 3 :(得分:0)
如果允许/保护可选值以避免崩溃,最好使用它。
if let viewControllers: [UIViewController] = self.navigationController.viewControllers{
for VC in viewControllers {
if (VC.isKind(of: HomeViewController.self)) {
bScreen = true
self.navigationController?.popToViewController(VC, animated: true)
}
}
if bScreen == false
{
let homeVC = HomeViewController()
self.navigationController?.pushViewController(homeVC, animated: false)
}
}
答案 4 :(得分:0)
永远不要直接使用!
,直到你确定它不会是零。替换您的代码如下。您可以使用if let
或guard let
来展开选项。
if let viewControllers: [UIViewController] = self.navigationController?.viewControllers {
for VC in viewControllers {
if (VC.isKind(of: ViewController.self)) {
bScreen = true
self.navigationController?.popToViewController(VC, animated: true)
}
}
if bScreen == false
{
let homeVC = ViewController()
self.navigationController?.pushViewController(homeVC, animated: false)
}
}
else {
// IF VC is nil
}
答案 5 :(得分:0)
根据您的代码,在循环中,如果导航堆栈包含相应的视图控制器,则会弹出相应的页面。但问题是如果同一个视图控制器出现两次,将导致同时执行循环。这可能会导致崩溃。所以在poptoviewcontroller之后添加一个休息时间可以避免这个问题。请检查以下代码,将为您提供帮助。
if (VC.isKind(of: HomeViewController.self)) {
bScreen = true
self.navigationController?.popToViewController(VC, animated: true)
break
}