HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Fetching tweets

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fetchingtweetsstackoverflow

Problem

I have written this (truncated) code to fetch some tweets:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSString *JSONStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://search.twitter.com/search.json?q=haak&lang=nl&rpp=100"] encoding:NSUTF8StringEncoding error:nil];
    if (!JSONStr) {
      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
      return;
    }

    /*... PARSING ETC ...*/

    dispatch_sync(dispatch_get_main_queue(), ^{
      [delegate didReceiveTweets:foundTweets];
    });

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  });


Note the lines from dispatch_sync(dispatch_get_main_queue(), ^{ to });. This will update the UI.

Is this the good way to do it, or are there better ways than using dispatch_sync within a dispatch_async? Or should I not do this at all? Should I also send setNetworkActivityIndicatorVisible: from within the main thread?

The reason I'm not using NSURLConnection is because this code comes from a class method, so I need to create an object containing the delegate for the NSURLConnection, which seems overkill to me.

Solution

you don't necessarily have to call -setNetworkActivityIndicatorVisible: from the main thread. I didn't find anything in the documentation about UIApplication not being thread safe, and since your application's main thread doesn't have anything in common with the system, you are free to call it whenever you like.

dispatch_sync: that's fine. you could also call dispatch_async, since i'm not really sure you would want do display the network indicator while the feeds are actually being set on the UI - instead you probably only want the downloading to be indicated. I would probably go for dispatch_async.

But to answer your question, that piece of code is perfectly fine ( with the minor addition that maybe you should really use only one exit point from your method ... )

Hope this helps.

Context

StackExchange Code Review Q#112, answer score: 7

Revisions (0)

No revisions yet.