1
let url = NSURL(string: "http://api.mdec.club:3500/news?")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
    (data, response, error) in

    self.jsonResult = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray

    self.tableView.reloadData()
}

task.resume()

I don't understand why I'm getting this error. I have to put the reloadData() method inside task because I have to wait till the get the data. How else can I reload the table view without getting this error?

Schuey999
  • 4,706
  • 7
  • 21
  • 36

1 Answers1

1

How else can I reload the table view without getting this error?

You step out to the main thread in order to call reloadData, like this:

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
    (data, response, error) in
    self.jsonResult = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }
}

Always do that any time you touch the interface from code that was called on a background thread. You must never never never never touch the interface except on the main thread.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    Actually, it isn't very wise to modify `self.jsonResult` on a background thread either, so you might want to put _both_ lines inside the `dispatch_async` call. – matt Nov 15 '15 at 02:52
  • it works thanks! Will accept answer in 4 minutes. ;) – Schuey999 Nov 15 '15 at 02:53
  • matt can you explain why just so I know why I'm doing what I'm doing if I put the jsonResult in the dispatch – Schuey999 Nov 15 '15 at 02:53
  • 1
    The correct thing to do would be to do the deserialization in the background, then the assignment to `self.jsonResult` on the main queue just before the reload. – nhgrif Nov 15 '15 at 03:23
  • @nhgrif very good point, I had not teased it far enough apart – matt Nov 15 '15 at 04:05
  • @nhgrif but why? (just want to know) – Schuey999 Nov 15 '15 at 21:24
  • @Schuey999 Which part are you asking why about? – nhgrif Nov 15 '15 at 23:41
  • @nhgrif why the jsonResult should not be on the background thread – Schuey999 Nov 15 '15 at 23:52
  • Because presumably you're using `jsonResult` as the data for your table. If you modify it in the background, you can get something like an index out of bounds if say your table was originally loading 10 rows, but you just overwrote `jsonResult` with something that would only have 3 rows. – nhgrif Nov 15 '15 at 23:55