self.tableView.reloadData() not working in Swift

前端 未结 10 1019
离开以前
离开以前 2020-12-23 09:12

I\'m attempting to learn Swift & the basics of iOS dev at the same time, so bear with me. I\'ve got a TableViewController that is

相关标签:
10条回答
  • 2020-12-23 09:52

    All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.

    Swift 4

    DispatchQueue.main.async{
        self.tableView.reloadData()
    }
    
    0 讨论(0)
  • 2020-12-23 09:58

    I was also facing the same issue, what I did wrong was that I'd forgot to add

    tableView.delegate = self    
    tableView.dataSource = self
    

    in the viewDidLoad() {} method. This could be one reason of self.tableView.reloadData() not working.

    0 讨论(0)
  • 2020-12-23 09:59

    If your connection is in background thread then you should update UI in main thread like this

    self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)
    

    As I have mentioned here

    Swift 4:

    self.tblMainTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)
    
    0 讨论(0)
  • 2020-12-23 10:08

    You'll need to reload the table on the UI thread via:

    //swift 2.3
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tableView.reloadData()
    })
    
    //swift 5
    DispatchQueue.main.async{
        self.tableView.reloadData()
    }
    

    Follow up: An easier alternative to the connection.start() approach is to instead use NSURLConnection.sendAsynchronousRequest(...)

    //NSOperationQueue.mainQueue() is the main thread
    NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
        //check error
        var jsonError: NSError?
        let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
        //check jsonError
        self.collectionView?.reloadData()
    }
    

    This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded

    0 讨论(0)
提交回复
热议问题