在主线程上处理调度队列中的错误

handling errors within dispatch queue on the main thread

我有以下代码,试图思考如何通过以下后台调用实现 GCD(我是新手)。

不仅我必须在后台线程上调用 findAll,而且我还必须填充 table 视图(委托调用 UITableViewDataSource 实现,期望用户被填充),所以table 视图的数量必须有所延迟。

如果有更好的方法,请多多指教。 OperationQueue 是答案吗?

override func viewWillAppear(_ animated: Bool) {
    DispatchQueue.global().async { // network call for data
        print("global")
        
        DispatchQueue.main.async { // update UI
            print("main")
        }
    }
    
    do {
        users = try model?.findAll() // data for tableView
    } catch let error as NSError {
        print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
    }
}

func fault(_ error: NSError) {
     print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")

}

table 查看上下文

extension UserViewController: UITableViewDataSource {
    // number of rows
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        users?.count ?? 0
    }
    
    // cell contents
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath as IndexPath)
        cell.textLabel?.text = users?[indexPath.row].givenName
        return cell
    }
}

全部查找

func findAll() throws -> [User]? {
    var statement: OpaquePointer? = nil
    let sql = "SELECT * FROM user"
    
    guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK else {
        throw NSError(domain: String(cString: sqlite3_errmsg(database)), code: 1, userInfo: nil)
    }
    
    defer { sqlite3_finalize(statement) }
    
    var users: [User] = []
    while sqlite3_step(statement) == SQLITE_ROW {
        first: String(cString: sqlite3_column_text(statement, 2)), last: String(cString: sqlite3_column_text(statement, 3))))
    }
    return users
}

您可以在加载数据时在 table 视图中显示一些占位符视图。数据可用后,删除占位符视图并使用数据更新 table 视图。