5.16. Creating Concurrency with Threads

Problem

You would like to have maximum control over how separate tasks run in your application. For instance, you would like to run a long calculation requested by the user while freeing the main UI thread to interact with the user and do other things.

Solution

Utilize threads in your application, like so:

- (void) downloadNewFile:(id)paramObject{
  
  @autoreleasepool {
    NSString *fileURL = (NSString *)paramObject;
    
    NSURL    *url = [NSURL URLWithString:fileURL];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLResponse *response = nil;
    NSError       *error = nil;
    
    NSData *downloadedData = 
    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response
                                      error:&error];
    
    if ([downloadedData length] > 0){
      /* Fully downloaded */
    } else {
      /* Nothing was downloaded. Check the Error value */
    }
  }
  
}

- (void)viewDidLoad {
  [super viewDidLoad];
  
  NSString *fileToDownload = @"http://www.OReilly.com";
  
  [NSThread detachNewThreadSelector:@selector(downloadNewFile:) 
                           toTarget:self 
                         withObject:fileToDownload];
  
}

Discussion

Any iOS application is made out of one or more threads. In iOS 5, a normal application with one view controller could initially have up to four or five threads created by the system libraries to which the application is linked. At least one thread will be created for your application whether you use multiple threads or not. It is called the “main UI thread” attached to the main run loop.

To understand how useful threads are, let’s do an experiment. ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.