Swift - 在前台输入的reloadData UITableView

时间:2018-01-23 18:28:26

标签: ios swift uitableview

当我返回前景时,我想调用reloadData TableView方法。我的TableView是以编程方式构建的。

FirstViewController我填写TableView的方法和我调用reloadListOfApps方法的函数reloadData

class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate {     

    @IBOutlet weak var listOfApps: UITableView!

    override func viewDidLoad() {
            super.viewDidLoad()
            listOfApps.delegate = self
            listOfApps.dataSource = self
    }

    func reloadListOfApps() {
        listOfApps.reloadData()
    }    

// ================ TABLE DELEGATE/MANAGER ===================

let apps = ListAppClass.listApp()

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return apps!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()

    let bundle = apps! [indexPath.row]
    let bundle_temp = String(describing: bundle)

    cell.textLabel?.text = bundle_temp
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Current Cell!")

}
}

AppDelegate

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    FirstViewController().reloadListOfApps()
}

当我运行应用程序时,我发现了此错误

  

致命错误:在解包可选值时意外发现nil

阅读some questions我还检查了故事板中的奥特莱斯,似乎一切正常。

Hooks对应FirstViewController

错误在哪里?

1 个答案:

答案 0 :(得分:3)

尝试在视图控制器中添加oberver

NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillEnterForeground),
name: .UIApplicationWillEnterForeground,
object: nil)

回调

@objc func applicationWillEnterForeground() {

     listOfApps.reloadData()

}

////问题解释

在AppDelegate中编写此代码时

  FirstViewController().reloadListOfApps()

这会动态创建一个实例,其所有属性都是nil,因为你没有加载storybaord对象或与之关联的Xib文件没有从当前活动对象中显示出来,控件转到 reloadListOfApps < / strong>功能并发现你要重新加载的 listOfApps 是nil所以崩溃发生,上面的解决方案是一种方式,另一种方法是使用委托或使 listOfApps 共享可以在任何地方引用的对象