2016-06-22 70 views
1

當我運行這段代碼,它工作正常,但是當我在dispatch_async運行它,它在tableViews功能numberOfRowsInSectionArray獲取無GCD

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

+0

您可以嘗試將'return self.data.count'更改爲'return self.data.count ?? 0' –

+0

顯示您的代碼!什麼是'self.dataOfJson'?你的代碼如何實現'numberOfRowsInSection'和其他兩個重要問題? – matt

+0

當self.data爲零時,調用count爲零會導致EXC_BAD_INSTRUCTION RED ERROR。你必須檢查是不是無 – Cruz

回答

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() 
    } 
} 
+0

仍然無法正常工作:/ –

+0

感謝它的工作..我做了一些修改..但非常感謝 –