0

I am trying to figure out if this code is updating the UI on the main thread. This code is in a class I made specifically for downloading the JSON feed. After getting the data, I parse it to return an array I will use to update the UI, and then let the delegate know the data is ready. My delegate, a view controller, will use this array to update the UI. Do I need to do the -parser:didFinishParsingWithResults: in a dispatch_get_main_queue block? Or is that not necessary since I am updating UI in the view controller class and not this class? Thank you!

__block NSArray *results;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *responseData = [NSData dataWithContentsOfURL:url];
    results = [self parseData:responseData];
    [self.delegate parser:self didFinishParsingWithResults:results];
});
bdash
  • 18,110
  • 1
  • 59
  • 91
James Kuang
  • 10,710
  • 4
  • 28
  • 38

2 Answers2

3
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

That ain't the main thread. That is the default priority global queue which might be any thread.

If parser:didFinishParsingWithResults: diddles UI elements without dispatching to the main queue / thread, then you have a problem.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • Got it! I just wasn't sure if telling the delegate means it automatically goes back onto the main thread. Don't know why I made such an assumption. Thank you. – James Kuang Aug 05 '12 at 05:45
2

Definitely use dispatch_get_main_queue() to update your UI, that code's not thread safe, so you'll always want to update your UI on the main thread. I learned this the hard way :-)

MattR
  • 6,908
  • 2
  • 21
  • 30