我已经声明了一个数组并通过互联网获取数据来启动它。我希望它在UITableView init之前插入,因为它是为了填充UITableView的单元格,但显然它没有。我可以做些什么来改进代码 终端打印 1 2 2 2 3 4 4 我想要它打印 1 4 4 2 2 2 3
HttpController.swift
import UIKit
protocol HttpProtocol{
func didRecieveResults(results:NSDictionary)
}
class HttpController:NSObject{
var delegate:HttpProtocol?
func onSearch(url:String){
var nsUrl:NSURL = NSURL(string:url)!
var request:NSURLRequest = NSURLRequest(URL: nsUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse!,data:NSData!,error:NSError!)->Void in
var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
self.delegate?.didRecieveResults(jsonResult)
})
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,HttpProtocol {
@IBOutlet weak var tv: UITableView!
@IBOutlet weak var iv: UIImageView!
@IBOutlet weak var playTime: UILabel!
@IBOutlet weak var progressView: UIProgressView!
var eHttp:HttpController = HttpController()
var tableData:NSArray = NSArray()
var channelData:NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
eHttp.delegate = self
eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
println(1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
println(2)
return 1//tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!{
println(3)
let cell = UITableViewCell(style:UITableViewCellStyle.Subtitle,reuseIdentifier:"douban")
// let rowData:NSDictionary = self.tableData[indexPath.row] as! NSDictionary
cell.textLabel!.text = "hehehehe"//rowData["title"] as! String
cell.detailTextLabel!.text = "adasdasda"//rowData["artist"] as! String
return cell
}
func didRecieveResults(results:NSDictionary){
println(4)
if (results["song"] != nil){
self.tableData = results["song"] as! NSArray
}else if (results["channels"] != nil){
self.channelData = results["channels"] as! NSArray
// println(channelData)
}
}
}
答案 0 :(得分:2)
在初始化表视图之前,当数据阵列准备就绪时,不需要初始化数组 - 只需调用
即可[tableView reloadData];