[英]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. 在我的iOS应用中,我有一个SQLite数据库,其中的
items
表有很多行。 I'm avoiding loading all of the items into memory and instead only loading the ones being currently shown in the UITableView
. 我避免将所有项目加载到内存中,而是仅加载当前在
UITableView
显示的项目。
I'm using SQLite.swift which can throw
when interacting with the database. 我正在使用SQLite.swift ,当与数据库进行交互时会
throw
该异常 。 If getting the count from the items
table does throw
, what's the right thing to do? 如果从
items
表中获取计数确实throw
,那该怎么办?
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. Items
类是这样的。
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. 如果使用DZNEmptyDataSet之类的东西,则可以在视图控制器上使用状态变量,并使用不同的状态,例如.loading,.showing,.empty,.error。 For any state other than .showing you would return 0 for number of rows and let the DZNEmptyDataSet display instead.
对于.showing以外的任何状态,您将返回0作为行数,而改为显示DZNEmptyDataSet。 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.
因此,例如,如果数据加载失败,则将状态设置为.error,然后调用tableView.reloadData(),该方法将调用emptySetDatasource方法,您可以在其中指定错误消息。 If you have a refresh control the user can pull to refresh and you put the state back to .loading and try again.
如果您具有刷新控件,则用户可以拉动刷新,然后将状态放回.loading,然后重试。 This is how table views backed by REST data work in most popular apps.
这就是REST数据支持的表视图在大多数流行应用中的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.