我是IOS和swift的新手。我正在尝试实现一个返回 json 然后将其显示在表中的 api get 请求。下面是我当前的代码。当我运行模拟器时,我收到以下错误:
致命错误:无法索引空缓冲区
如果我删除 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.
}
}
我发现了几个问题——
-
您的ViewController应该符合UITableViewDatasource(缺少,不确定它是如何做到的)
-
当 self.doDatItems 没有任何项时,不要返回 3。它会导致崩溃。只要数据加载,表就保持为空。返回 self.doDatItems.count
-
一旦数据加载并准备好从 self.doDatItems 数组显示,只需调用表视图的 reloadData() 方法即可。
-
在此之前,你应该有一个表视图的引用(或IBOutlet),以便你可以从任何地方调用reloadData()。
您需要在接收并解析数据后触发页面刷新。
类似的东西
self.tableView.reloadData()
在这个返回行数的委托方法中,
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
不要将静态数字用作 3。获取您的数组计数并在此处返回计数。
json 响应出现后,重新加载表视图。在 objective-c 中,它由
[tableView reloadData];