变量仅在sendAsynchronousRequest中更新

时间:2014-11-15 20:43:16

标签: swift sendasynchronousrequest

我不想做的事情的例子:

var b  = 0

let URL: NSURL = NSURL(string: "[URL to php file]")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
    (response, data, error) in
    b = 5
}

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return b //Return 0
}

我知道在numberOfRowsInSection中它返回0导致sendAsynchronousRequest执行之后 但是有没有办法让sendOynchronousRequest后执行numberOfRowsInSection函数?或者是否有更好的方法使我的变量在numberOfRowsInSection函数之前等于5?

1 个答案:

答案 0 :(得分:1)

您不希望延迟numberOfRows...来电,但在异步请求中收到数据后,您可以致电tableView.reloadData

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
    (response, data, error) in
    b = 5
    self.tableView.reloadData()
}

这将使表格视图重新配置并再次调用numberOfRows...