如何更新tableview json

时间:2016-04-23 16:12:21

标签: ios json swift

我想在更改mysql数据库中的数据后更新我的tableview数据,但它不起作用。在我的parsejson函数中,我试过:

 dispatch_async(dispatch_get_main_queue(),{

                    self.movies = movieArray
                    self.tableView.reloadData()

当然这不起作用,因为这个函数不在tableviewcontroller中,所以它不能识别tableview。是否可以从tableviewcontroller以外的其他文件中的函数重新加载tableview?如何?

此致

2 个答案:

答案 0 :(得分:0)

更新数据后,通知你的tableviewController更新它的模型,然后重新加载你的tableview。

答案 1 :(得分:0)

使用Swift Closures

部分代码如下:

DataLoader.swift

class DataLoader: NSObject {

    func uploadData(completion: ([AnyObject]) -> () ) {
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0)) {
            let array = [1, 2, 3, 4] //load your data in background thread
            dispatch_async(dispatch_get_main_queue()) {
                completion(array) //send completion in main thread
            }
        }
    }
}

ViewController.swift

class ViewController: UIViewController { 
    let dataLoader = DataLoader()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.dataLoader.uploadData {
            (any) in
            if let movieArray = any as? [Int] { //Here instead of [Int] should be your array of objects e.g. [Movies]
                print("result: \(movieArray)")
                self.movies = movieArray
                self.tableView.reloadData()
            }
        }
    }
}