【发布时间】:2015-01-22 15:46:44
【问题描述】:
我是 IOS 新手,速度很快。我正在尝试实现一个返回 json 然后将其显示在表格中的 api 获取请求。以下是我当前的代码。当我运行模拟器时,出现以下错误:
致命错误:无法索引空缓冲区
如果我删除 tableView 函数中的硬编码返回 3 并改用 doDatItems.count ,则表中不会呈现任何内容,因为我猜 doDatItems 数组在发出 get 请求之前开始为空。这似乎是一个时间问题?如何确保在表加载之前发出 get 请求?
import UIKit
class ViewController: UIViewController, UITableViewDelegate {
var doDatItems:[String] = []
@IBOutlet weak var doDatItem: UITextField!
@IBOutlet weak var yourDoDats: UILabel!
@IBAction func addDoDat(sender: AnyObject) {
doDatItems.append(doDatItem.text)
println(doDatItems)
}
override func viewDidLoad() {
super.viewDidLoad()
let urlPath = "http://localhost:3000/dodats"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if((error) != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
} else {
let dataArray = jsonResult["dodats"] as [String]
for item in dataArray {
self.doDatItems.append(item)
}
// println(self.doDatItems)
}
})
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
println(self.doDatItems)
cell.textLabel?.text = self.doDatItems[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
【问题讨论】:
标签: ios json uitableview tableview