首页 > 解决方案 > 当无法找到故事板或尚未创建故事板时,如何防止 SWIFT 4.2 运行时错误?

问题描述

我正在做一个为期 30 天的课程来学习 SWIFT 4.2,并且启动项目有一个表格视图来展示 30 个应用程序,每天一个。因此,有特定日期的故事板。

这是代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    var dataModel = NavModel.getDays()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)

    }

    // MARK: uitableview delegate and datasource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print ("This is dataModel.count: ", dataModel.count)
        return dataModel.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContentTableViewCell
        cell.data = dataModel[indexPath.row]
        print(cell.data!)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dayCount = dataModel[indexPath.row].dayCount
        print("This is dayCount: ", dayCount)
        let initViewController = UIStoryboard(name: "Day\(dayCount)", bundle: nil).instantiateInitialViewController()
        self.navigationController?.pushViewController(initViewController!, animated: true)

    }
}

如何更新此代码段:

let initViewController = UIStoryboard(name: "Day\(dayCount)", bundle: nil).instantiateInitialViewController()

如果应用程序找不到尚不存在的特定情节提要,以防止应用程序崩溃?

这是 NavModel.swift 的代码:

import UIKit 

class NavModel { 

    var dayCount: Int 
    var title: String 
    var color: UIColor 

    init(count: Int, title: String, color: UIColor) { 
        self.dayCount = count 
        self.title = title 
        self.color = color 
    } 

    class func getDays() -> [NavModel] { 
        var model = [NavModel]() 
        for i in 1...30 { 
            let nav = NavModel(count: i, title: "Day (i)", color: UIColor.randomFlatColor()) 
            model.append(nav) 
        } 
        return model 
    }
}

标签: iosswiftstoryboard

解决方案


您无法阻止该代码崩溃。无法找到引用的故事板是无法捕获的致命错误。

引用不是您的捆绑包的情节提要是您在测试期间想要了解的内容。

适当的解决方案是更改数据模型,使其仅包含您有故事板的数据。即,如果今天是第 10 天,则NavModel.getDays()应该只返回 10 个数据项。

会重写NavModel为:

import UIKit

struct NavModel {

    let dayNumber: Int
    var title: String {
        get {
            return "Day \(dayNumber)"
        }
    }
    let color: UIColor


    static func getDays(count: Int) -> [NavModel] {
        var model = [NavModel]()
        for i in 1...count {
            model.append(NavModel(dayNumber: i, color: UIColor.randomFlatColor()))
        }
        return model
    }
}

然后创建模型,比如说,NavModel.getDays(count:10)


推荐阅读