我是iOS的新手,我通过解析JSON数据从web源动态填充tableView数据。但问题是,当我第一次访问该标签时,它什么都没显示。在我访问另一个选项卡并返回后,它在tableView上正确显示数据。
这是我的代码
import UIKit
class BranchViewController: UITableViewController , UISearchBarDelegate, UISearchDisplayDelegate {
var branches = [Branch]()
var filteredBranch = [Branch]()
var BranchArray = [BranchTable]()
var BranchLocationArray = [BranchLocation]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView!.delegate = self
self.tableView!.dataSource = self
let url = NSURL(string: "http://rana.ninja/branches.php")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var error: NSError?
let jsonData: NSData = data /* get your json data */
let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
if let name: AnyObject = json["name"] {
for var index = 0; index < name.count; ++index {
var Name : String = name[index] as NSString
self.branches.append(Branch(name: Name))
println(Name)
}
}
}
task.resume()
BranchArray =
[BranchTable(BranchTitle: ["FirstFirst","SecondFirst","ThirdFirst"]),
BranchTable(BranchTitle: ["FirstSecond","SecondSecond","ThirdSecond"]),
BranchTable(BranchTitle: ["FirstThird","SecondThird","ThirdThird"]),
BranchTable(BranchTitle: ["FirstFourth"])]
BranchLocationArray = [BranchLocation(BranchLocationValues: ["asdfasd","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"])]
// Reload the table
self.tableView.reloadData()
}
答案 0 :(得分:3)
更新数据结构后,需要调用tableView.reloadData
。这必须在主线程中完成,因此:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var error: NSError?
let jsonData: NSData = data /* get your json data */
let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
if let name: AnyObject = json["name"] {
for var index = 0; index < name.count; ++index {
var Name : String = name[index] as NSString
self.branches.append(Branch(name: Name))
println(Name)
}
}
// NOTE: Calling reloadData in the main thread
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
答案 1 :(得分:1)
看来,您的数据加载是异步完成的,但是您正在重新加载闭包之外的表,因此可能会在加载完成之前执行。因此,您可以将表重新加载到闭包中。
而且,建议的排队方式很好,您可以在Apple doc中阅读GCD:
dispatch_async(dispatch_get_main_queue()) {
// Assign Job To The Main Queue
}
dispatch_async
在调度队列上提交异步执行块并立即返回。它有两个参数 - queue
;要提交块的队列&amp; block
要提交的工作。