Ios 从远程数据库填充UITableView单元格

Ios 从远程数据库填充UITableView单元格,ios,swift,uitableview,ios9,Ios,Swift,Uitableview,Ios9,我正面临一个与UITableView有关的问题 我想用从远程数据库获取的数据动态地填充它的单元格,所以在数据到达之前需要一些时间 代码如下: class MailBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var users: [NSDictionary] = [] override f

我正面临一个与UITableView有关的问题

我想用从远程数据库获取的数据动态地填充它的单元格,所以在数据到达之前需要一些时间

代码如下:

class MailBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var users: [NSDictionary] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // call to rest API code to get all users in [NSDictionary]
    (...)

    // set table view delegate and data source
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

// set number of sections within table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

// set number of rows for each section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return self.users.count
    }
    return 0
}

// set header title for each section
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Users"
    }
}

// set cell content for each row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // deque reusable cell
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    // set item title
    if indexPath.section == 0 {
        cell.textLabel?.text = self.users[indexPath.row]["firstname"] as? String
    }
    return cell
}
}
问题是,当调用tableView函数为每个部分设置行数并为每行设置单元格内容时,my[NSDictionary]用户仍然为空

只有在调用rest API代码以获取[NSDictionary]中的所有用户完成后,我如何才能设置行和单元格

谢谢你的反馈


关于

当您从API获得响应时,您应该设置
self.users=ArrayFusersYourReceivedFromServer
,然后调用
self.tableView.reloadData()
。这

当您从API获得响应时,应该设置
self.users=ArrayFusersYourReceivedFromServer
,然后调用
self.tableView.reloadData()
。此

在填充
用户
后,调用
tableView.reloadData()
。这将再次调用数据源方法。

填充
用户后,调用
tableView.reloadData()
。这将再次调用您的数据源方法。

当您完成获取用户调用时。

当您完成获取用户调用时。

是的,但当第一次调用数据源方法时,self.users为空,因此它因数组越界异常而崩溃。我看不出您将如何超出范围。返回用户数的数组计数。如果没有任何用户,则不会调用
cellforrowatinexpath:
方法。是的,但是当第一次调用数据源方法时,self.users为空,因此它会因为数组越界异常而崩溃。我不知道您在这里会如何越界。返回用户数的数组计数。如果没有任何用户,则不会调用
cellforrowatinexpath:
方法。