NSArray更改后UITableView不会更新

时间:2015-09-06 13:57:51

标签: ios swift uitableview

我有HTTP异步请求,我想阅读JSON并填写我的视图。

我获取数据请求,我制作NSArray,但我可以在我的函数中传递它,tableView numberOfRowsInSection只返回1,请帮助。

import Foundation

import UIKit

class ThirdView : UITableViewController {

var jsonz:NSArray = ["Ray Wenderlich"];
let url = NSURL(string: "http://iweddings.ru/xmlrestaurant.json");

override func viewDidLoad() {

    super.viewDidLoad()

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSArray
        println(json)
// here i see in xCode output
//        price = 4500;
//        rating = 45;
//        slogan = "\U041d\U0435\U043b\U0435\U0433\U0430\U043b\U044c\U043d\U043e";
//        status = 1;
//        type = 1;
// etc....


            self.jsonz = json;
    }

    task.resume()


}


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1;
}

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

    println(self.jsonz.count);
    return self.jsonz.count;
// here i see always "1" ???? why?
}

NSArray jsonz 不会改变。 抱歉我的英文。

1 个答案:

答案 0 :(得分:1)

您需要在下载json数据后调用reloadData()方法:

class ThirdView: UITableViewController {
    var jsonz: NSArray = ["Ray Wenderlich"]
    let url = NSURL(string: "http://iweddings.ru/xmlrestaurant.json")

    override func viewDidLoad() {
        super.viewDidLoad()

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSArray
            println(json)

            self.jsonz = json;
            self.tableView.reloadData()
        }

        task.resume()
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

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