【问题标题】:IOS/Swift rendering table after JSON requestJSON请求后的IOS/Swift渲染表
【发布时间】: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


    【解决方案1】:

    我发现了几个问题——

    1. 您的 ViewController 应该符合 UITableViewDatasource(缺少,不知道它是怎么做到的)

    2. 当 self.doDatItems 没有任何项目时不返回 3。它会导致崩溃。只要数据加载让表保持为空。返回 self.doDatItems.count

    3. 一旦从 self.doDatItems 数组加载并准备好显示数据,只需调用表格视图的 reloadData() 方法即可。

    4. 在此之前,您应该拥有 tableView 的引用(或 IBOutlet),以便您可以从任何地方调用 reloadData()。

    【讨论】:

      【解决方案2】:

      在接收并解析数据后,您需要触发页面刷新。

      类似的东西

      self.tableView.reloadData()

      【讨论】:

        【解决方案3】:

        在这个返回行数的委托方法中,

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        

        不要将静态数字用作 3。获取您的数组计数并在此处返回计数。

        json响应来后,重新加载tableView。在objective-c中它是由

        完成的
        [tableView reloadData];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-19
          • 1970-01-01
          • 1970-01-01
          • 2018-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多