2016-10-22 65 views
0

在我的iOS应用程序中,我有一个SQLite数据库,它有一个包含许多行的items表。我避免将所有项目加载到内存中,而只是加载当前显示在UITableView中的项目。在tableView(_:numberOfRowsInSection :)中抛出错误时该怎么办?

我在使用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 
    } 

    // ... 
} 

回答

0

如果你使用类似DZNEmptyDataSet那么你可以有你的视图控制器的状态变量,有不同的状态,像.loading,.showing,.empty,.error。对于.showing以外的任何状态,您将返回0作为行数,并让DZNEmptyDataSet显示。因此,例如,如果您的数据未能加载,那么您将状态设置为.error,并调用tableView.reloadData(),它调用emptySetDatasource方法,您可以在其中指定错误消息。如果您有刷新控件,用户可以拉动刷新,并将状态恢复为.loading,然后重试。这是REST数据支持的表视图在大多数流行应用程序中的工作方式。

相关问题