[英]What to do when error thrown in tableView(_:numberOfRowsInSection:)?
在我的iOS應用中,我有一個SQLite數據庫,其中的items
表有很多行。 我避免將所有項目加載到內存中,而是僅加載當前在UITableView
顯示的項目。
我正在使用SQLite.swift ,當與數據庫進行交互時會throw
該異常 。 如果從items
表中獲取計數確實throw
,那該怎么辦?
我嘗試顯示一個警告,指出用戶無法像這樣關閉。
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
}
// ...
}
Items
類是這樣的。
class Items {
var connection: Connection
func getCount() throws -> Int {
return try connection.scalar("SELECT count(*) FROM items") as! Int
}
// ...
}
如果使用DZNEmptyDataSet之類的東西,則可以在視圖控制器上使用狀態變量,並使用不同的狀態,例如.loading,.showing,.empty,.error。 對於.showing以外的任何狀態,您將返回0作為行數,而改為顯示DZNEmptyDataSet。 因此,例如,如果數據加載失敗,則將狀態設置為.error,然后調用tableView.reloadData(),該方法將調用emptySetDatasource方法,您可以在其中指定錯誤消息。 如果您具有刷新控件,則用戶可以拉動刷新,然后將狀態放回.loading,然后重試。 這就是REST數據支持的表視圖在大多數流行應用中的工作方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.