从SwiftyJSON API分配已解析的JSON会显示错误

时间:2016-02-11 18:49:15

标签: ios json swift swifty-json

我最近从Objective-C更新到Swift,在以原生方式解析JSON时真的很混乱,所以在Stack Overflow上搜索时我发现了SwiftyJSON API,它真的很酷。将分析的JSON值分配给标签时出错。我已将结果存储在数组中,但在tableview上显示它时显示错误。

//Array where I store the parsed JSON
var categoryCount = [Int]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    getData()
}

func getData() {

    Alamofire.request(.GET, "http://www.artively.com/api/MobileApi/get_parent_category")
        .responseJSON { response in
            if let value = response.result.value {
                let json = JSON(value)
                self.parseJSON(json)
            }
        }
}

func parseJSON(json: JSON) {
    for result in json["data"].arrayValue {
        print("The count are",result["product_count"].int!)
        self.categoryCount.append(result["product_count"].int!)
    }

    print("The category count are", categoryCount.count)
}

最后,当我执行此代码时,应用程序崩溃了:

 cell.countLable.text =  "\(categoryCount[indexPath.row])"
      //Error appear in above code

这是JSON结果:

{
  "responsecode": "200",
  "responsemsg": "Successfull",
  "data": [
{
  "pk_category_id": 60,
  "category_name": "Collage",
  "category_logo": "http://www.artively.com//Upload/category_logo/28102015163738_collage_icon.png",
  "category_logo_selected": "http://www.artively.com//Upload/category_logo/28102015163738_collage_icon.png",
  "product_count": 10
},
{
  "pk_category_id": 65,
  "category_name": "Contemporary",
  "category_logo": "http://www.artively.com//Upload/category_logo/28102015163521_contempory_icon.png",
  "category_logo_selected": "http://www.artively.com//Upload/category_logo/28102015163521_contempory_icon.png",
  "product_count": 242
},
...So on

在上面的响应中,我解析了“product_count”的值,将其存储在一个数组中并将其显示在tableview单元格上,但应用程序崩溃...

1 个答案:

答案 0 :(得分:0)

解析后,您应致电self.tableView.reloadData()。然后还要确保您正在实现此方法:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.categoryCount.count
}

这将确保您的数组中只包含元素,因此indexPath.row不会超出数组边界。

相关问题