7.15. 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=[NSURLURLWithString:fileURL];NSURLRequest*request=[NSURLRequestrequestWithURL:url];NSURLResponse*response=nil;NSError*error=nil;NSData*downloadedData=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];if([downloadedDatalength]>0){/* Fully downloaded */}else{/* Nothing was downloaded. Check the Error value */}}}-(void)viewDidLoad{[superviewDidLoad];NSString*fileToDownload=@"http://www.OReilly.com";[NSThreaddetachNewThreadSelector:@selector(downloadNewFile:)toTarget:selfwithObject: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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access