简体   繁体   中英

What to do when error thrown in tableView(_:numberOfRowsInSection:)?

In my iOS app, I have a SQLite database with an items table that has many rows. I'm avoiding loading all of the items into memory and instead only loading the ones being currently shown in the UITableView .

I'm using SQLite.swift which can throw when interacting with the database. If getting the count from the items table does throw , what's the right thing to do?

I've tried showing an alert that the user cannot close like this.

class ItemsController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var items: Items!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var count = 0
        do {
            count = try items.getCount();
        }
        catch {
            // present a fatal error message
            let alert = UIAlertController(
                            title: "Fatal Error",
                            message: "\(error)",
                            preferredStyle: .alert)
            self.present(alert, animated: true, completion: nil)
        }
        return count
    }

    // ...
}

The Items class is something like this.

class Items {

    var connection: Connection

    func getCount() throws -> Int {
        return try connection.scalar("SELECT count(*) FROM items") as! Int
    }

    // ...
}

If you use something like DZNEmptyDataSet then you can have a state variable on your view controller and have different states, like .loading, .showing, .empty, .error. For any state other than .showing you would return 0 for number of rows and let the DZNEmptyDataSet display instead. So for instance if your data fails to load then you set the state to .error and call tableView.reloadData() which calls the emptySetDatasource methods, where you can specify an error message. If you have a refresh control the user can pull to refresh and you put the state back to .loading and try again. This is how table views backed by REST data work in most popular apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM