Creating TableViews in Swift with an Array

167 views Asked by At

I'm attempting to use the result of one Rest call as an input for my TableView. I've got an array named GamesList[String] that is synthesized in the viewDidLoad() function. This is the viewDidLoad() fuction:

override func viewDidLoad() {
    super.viewDidLoad()

    getState() { (json, error) -> Void in
        if let er = error {
            println("\(er)")
        } else {
            var json = JSON(json!);
            print(json);

            let count: Int = json["games"].array!.count
            println("found \(count) challenges")

            for index in 0...count-1{
                println(index);
                self.GamesList.append(json["games"][index]["game_guid"].string!);
            }
        }
    }
}

The problem is that the functions for filling the TableView get executed before my GamesList array is filled up. These are the functions that fill the TableView:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return GamesList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Game", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = GamesList[indexPath.row]
    cell.detailTextLabel?.text = GamesList[indexPath.row]
    return cell
}

How do I force the tables to get filled up (refreshed) after my array has been filled?

1

There are 1 answers

3
Özgür Ersil On BEST ANSWER

use self.tableView.reloadData() after you append your values

 getState() { (json, error) -> Void in
        if let er = error {
            println("\(er)")
        } else {
            var json = JSON(json!);
            print(json);

            let count: Int = json["games"].array!.count
            println("found \(count) challenges")

            for index in 0...count-1{
                println(index);
                self.GamesList.append(json["games"][index]["game_guid"].string!);
            }
            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()
            }
        }
    }