UITableView 不显示单元格(使用 swift )

UITableView does not display the cells (using swift )

我正在使用 xcode v6.4。我想在 table 视图中显示我从 AWS DynamoDB 获得的所有用户名称。我尝试了以下代码

import UIKit
class messagesTableViewController: UITableViewController {

var myData: Array<AnyObject> = []
override func viewDidLoad() {
    super.viewDidLoad()


    let exp = AWSDynamoDBScanExpression()

    //  exp.valueForKey("name")
    //    exp.scanFilter = [ "date" : cond ]

    self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in
        NSLog("Scan multiple values - success")
        let results = task.result as! AWSDynamoDBPaginatedOutput
        for r in results.items {
            let myItem: Item = r as! Item

            println(myItem.name)
            self.myData.append(myItem.name)

            println("\(self.myData)")

        }
        return nil
    })
}

func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! {

    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.scan(Item.self, expression: expression)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    println("\(myData.count)")
    return myData.count

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellID: String = "cell"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! inboxTableViewCell
    dispatch_async(dispatch_get_main_queue(), {


        cell.nameLabel.text = self.myData[indexPath.row] as? String

    })



    return cell

}

此处,打印命令 'println("(self.myData)")' 打印了正确的数据,但相同的数据未显示在 table 视图中。

此外,当我向数组添加静态值时,相同的代码可以正常工作并在 table 视图中显示单元格。例如,下面是我的代码:

import UIKit

class messagesTableViewController: UITableViewController {


var myDummy: Array<AnyObject> = []

override func viewDidLoad() {
    super.viewDidLoad()

    var i = 1
    myDummy = ["Amit", "Kushal", "Saurabh", "Harsh", "Swar"]

 }   



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myDummy.count

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellID: String = "cell"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! inboxTableViewCell
    dispatch_async(dispatch_get_main_queue(), {


        cell.nameLabel.text = self.myDummy[indexPath.row] as? String

    })



    return cell

}

如果有人能指导我解决这个问题,那将是一个很大的帮助。

下面是应该有效的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    let exp = AWSDynamoDBScanExpression()

    self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in
    println("Scan multiple values - success")
    let results = task.result as! AWSDynamoDBPaginatedOutput
    for r in results.items {
        let myItem: Item = r as! Item

        println(myItem.name)
        self.myData.append(myItem.name)

     }
     // THIS IS THE CODE YOU NEED TO ADD:
     tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic) // Or choose some other animation.
     return nil
  })
}

尝试删除 dispatch_async 部分并将 nameLabel 更改为 textLabel,如下所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! inboxTableViewCell


    cell.textLabel.text = self.myDummy[indexPath.row] as? String



    return cell

}

我终于明白了。这是更新后的代码。

import UIKit

class messagesTableViewController: UITableViewController {

var myData: Array<AnyObject> = []


override func viewDidLoad() {
    super.viewDidLoad()

    var i = 1

    let exp = AWSDynamoDBScanExpression()

    //  exp.valueForKey("name")
    //    exp.scanFilter = [ "date" : cond ]

    self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in
        NSLog("Scan multiple values - success")
        let results = task.result as! AWSDynamoDBPaginatedOutput
        for r in results.items {
            let myItem: Item = r as! Item

            println(myItem.name)
            self.myData.append(myItem.name)

            println("\(self.myData)")

        }

  // This is the change in code. It needs to be added because the AWS scan  gathers the data in a background queue and we need to get back to the main queue after the background task is completed and then reload the table view.
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData()
        });
        return nil
    })

}

func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! {

    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.scan(Item.self, expression: expression)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    println("\(myData.count)")
    return myData.count

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellID: String = "cell"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! inboxTableViewCell
    dispatch_async(dispatch_get_main_queue(), {


        cell.nameLabel.text = self.myData[indexPath.row] as? String

    })



    return cell

}



}

问题中的代码没有工作,因为AWS扫描在后台队列中收集数据,我们需要在后台任务完成后返回主队列,然后重新加载table视图。