数组获得nil GCD

时间:2016-06-22 16:10:11

标签: ios swift uitableview grand-central-dispatch

当我运行此代码时它工作正常,但是当我在dispatch_async中运行它时,它会在tableViews函数中发生错误numberOfRowsInSection

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
    self.data = self.dataOfJson("http://192.168.1.100/practice/studentCourseSelection.php?ID=\(NSUserDefaults.standardUserDefaults().objectForKey("currentUser")!)")
    self.RefreshTableView()
}

func RefreshTableView()
{
    dispatch_async(dispatch_get_main_queue()){
        self.tableView.reloadData()
    }
}
 func dataOfJson(url:String) -> NSArray
{
    var jsonArray : NSMutableArray = []

    let data = NSData(contentsOfURL: NSURL(string : url)!)
    jsonArray = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSMutableArray



     return jsonArray
}

enter image description here

1 个答案:

答案 0 :(得分:2)

您应该在主线程上修改self.data

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
    let data = self.dataOfJson("http://192.168.1.100/practice/studentCourseSelection.php?ID=\(NSUserDefaults.standardUserDefaults().objectForKey("currentUser")!)")
    self.RefreshTableView(data)    
}

func RefreshTableView(data: ??) {
    dispatch_async(dispatch_get_main_queue()){
        self.data = data
        self.tableView.reloadData()
    }
}