Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

5. Concurrency > 5.16. Creating Concurrency with Threads

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:/....

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint