Dispatching a thread in iOS

I want to do something intensive, like loading a picture from the net and it’s going to take a while. I don’t want to impact my users, they need to be doing something else while this works in the background. In short, I don’t want to block the main thread.

What to do? Welcome Grand Central Dispatch.

Here’s how easy this is.

1. I want to dispatch a high priority thread, asynchronously

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_queue_t main = dispatch_get_main_queue();
    dispatch_async(queue, ^{[self loadMyPicture]; dispatch_async(main, ^{[self loadMyPictureDone]; }); });

2. Here’s your two methods, the loadMyPicture does something that’s going to take a while.

- (void)loadMyPictureDone {
    NSLog(@"loadMyPictureDone called");

- (void)loadMyPicture {
    NSLog(@"loadMyPicture called");
    NSData *imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    UIImage *pictureImage = [UIImage imageWithData:imageData];
    _myPictureImageView.image = pictureImage;

I mean, come on, you know that’s easy.

Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: