将数据打印到TableView(Swift)的问题

时间:2015-08-05 18:13:58

标签: arrays json swift tableview

我的功能是将http请求和结果保存到2个数组

然后我调用tableViewObejct.reloadData()将结果显示到tableView。但如果我在第一次功能后做第二次 - 没有任何反应。我要将我的函数调用到viewDidLoad,然后我有一个按钮,我正在做reloadData(),之后我才能在tableView中看到我的数据。

功能

func refreshData(){
     self.myData.removeAll(keepCapacity: true)
     self.ids.removeAll(keepCapacity: true)
     httpGet("https://money.yandex.ru/api/categories-list") { result in
         let json=JSON(data: result)
         println(json[0]["subs"].count)
         for var i=0; i<json.count; ++i {
             self.myData.append(json[i]["title"].stringValue)
             self.ids.append("")
             for var g=0; g<json[i]["subs"].count;++g {
                 self.myData.append("    "+json[i]["subs"][g]["title"].stringValue)
                 self.ids.append(json[i]["subs"][g]["id"].stringValue)
             }
         }
         println(self.myData.count)
         println(self.ids.count)
     }
}

myData是全局公共字符串数组,ids - 也是

tableView的函数:

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

func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell
{
     let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
     cell.textLabel!.text = myData[indexPath.row]
     return cell
}

所以我需要同时调用refreshData-function并在tableView中查看结果,只需viewDidLoad或单击按钮即可。为什么我必须将这些行为分开以查看tableView中的数组数据?

2 个答案:

答案 0 :(得分:1)

尝试从服务器获取数据时以这种方式重新加载tableView:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}

你的代码就像这样:

func refreshData(){
    self.myData.removeAll(keepCapacity: true)
    self.ids.removeAll(keepCapacity: true)
    httpGet("https://money.yandex.ru/api/categories-list") { result in
        let json=JSON(data: result)
        println(json[0]["subs"].count)
        for var i=0; i<json.count; ++i {
            self.myData.append(json[i]["title"].stringValue)
            self.ids.append("")
            for var g=0; g<json[i]["subs"].count;++g {
                self.myData.append("    "+json[i]["subs"][g]["title"].stringValue)
                self.ids.append(json[i]["subs"][g]["id"].stringValue)
            }
        }
        println(self.myData.count)
        println(self.ids.count)
        dispatch_async(dispatch_get_main_queue()) {
            self.tableView.reloadData()
        }
    }
}

答案 1 :(得分:0)

有点难以理解这个问题,但我认为正在发生的事情是,当您致电tableView.reloadData()时,您的GET请求尚未完成。现在我不知道httpGet函数的内部实现,但我会假设它是异步的。这意味着您的tableview在请求完成之前正在读取数据。

相关问题