O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.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, 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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required