Synchronous & Asynchronous Loading of data/images coupled with Multi-Threading (PART 2 – Application)

Synchronous vs Asynchronous Loading of data - Application to iOS - Tutorial with Examples

This post is a continuation of the previous post (Synchronous & Asynchronous Loading of data/images coupled with Multi-Threading (PART 1 – Conceptual)), which explained the concepts of Synchronous/Asynchronous loading & Multi-threading using day-to-day dating example. In this post, we will see the application of the concepts explained in Part 1 as applied to iOS. We will create a sample application  in which we explore two different situations. (Two methods called upon pressing two buttons):

Situation 1: Load a text file (text data) from a URL. In the this example, we load the text file synchronously.

Situation 2: Create a queue (NSOperationQueue) and then define an operation (NSInvocationOperation) which loads the same file; except that now it loads it in a different thread.

The size of the text file is around 1 MB so it takes few moments to download. While the text file loads, we can visually assess the progress of the app.

In both methods, the loading of the text file is followed by the asynchronous loading of an image from a URL. The image is around 100 KB (one-tenth the size of the text file.) As the last step, in both the methods we change the background color of the main view of the application from white (default) to black.

Let us understand the organization of the GUI of the app. It primarily comprises two controls, one to display the downloaded text file (a UITextView) and the other to display the downloaded image (a UIImageView). The main view of the application’s ViewController also has three buttons titled “Sequential Loading”, “Multi-Threaded Loading” and “Reset”. The default background color of the main view is white, which is changed to black in both the methods, as the last step in the execution of the code.

Now let us look at the code of the two methods.

The following method is called by pressing button titled “Sequential Loading”.

//========================================================================
//Loads the text file using the main thread of the application. Only when
//the text data has been downloaded, loading of image starts. The image
//is downloaded asnynchronously without affecting rest of the application
//========================================================================
-(IBAction)sequentialLoading:(id)sender{

    //Load the text file data (using the main application thread)
    [self loadTextFile];

    //Update textview to indicate that loading has commenced
    tvTextData.text = @"LOADING COMMENCED...";

    //Start Asynchronous Loading of Image
    [self loadImageAsynchronously];

    //Change the background color of main view to black
    self.view.backgroundColor = [UIColor blackColor];
}

What to Observe during the execution of the button handler?
When line 09 is executed, it is a synchronous operation and everything else stops. Even the blue color (highlighted color of the UIButton) remains blue. Only when the file is downloaded and shown in the text view, the image starts loading. While downloading of the text file is in progress (which takes some time,) the loading of the image and the change of the background color, both are on hold. Only after the text file is loaded, the remaining code executes.

It is interesting to note that while image is being downloaded and the image view is still blank, the background color of the main view of the app changes to black. This is so because the loading of the image is an asynchronous process and does not affect the rest of the application’s execution.

The following method is called by pressing button titled “Multi-Threaded Loading”.
(Important: Please press the “Reset” button, which clears both the text view and the image view, before you press the “Multi-Threaded Loading”.)

//========================================================================
//Loads the text file using another thread using a Queue. Downloading of
//the text file and images starts concurrently. Since the loading of
//the image is an asynchrounous operation the background color of the
//view is changed immediately to black (it does not wait for the image
//to download completely)
//========================================================================
-(IBAction)multiThreadedLoading:(id)sender{

    //Load the text file data (using multi-threading)
    [self loadTextFileByQueueing];

    //Update textview to indicate that loading has commenced
    tvTextData.text = @"LOADING COMMENCED...";

    //Start Asynchronous Loading of Image
    [self loadImageAsynchronously];

    //Change the background color of main view to black
    self.view.backgroundColor = [UIColor blackColor];

}

What to Observe during the execution of the button handler?
Here we start downloading the text file by creating an NSOperationQueue object, which allows us to load it on a different thread than the application’s main thread. As a result of this the code following the line 11 does not get affected and proceeds nevertheless. Immediately after the loading of the text file starts, the synchronous loading of image also commences. Not only this, as soon as we press the button the background color of the application also changes to black. You will observe that during the execution of the program, the text file takes more time to load in the text view than the image in the image view, as the text file is almost 10 times larger (approximately 1 MB) than the image file in size (KBs) (approximately 100 KB).

Synchronous Loading vs Asynchronous Loading – When to use which?

While designing apps, whenever we have situations where we have to execute tasks simultaneously we should carry them out on different threads. With NSOperationQueue class it is really very simple to do multi-threading as compared to resorting to NSThread class. When we wish to take advantage of the various delegate methods associated with NSURLConnection class, we can use asynchronous loading. Essentially both the approaches (NSOperationQueue or NSURLConnection) do not affect the execution of the main thread of the application.

A Word of Caution:
An important thing to note is that whenever we use NSInvocationOperation (along with NSOperationQueue) to execute a method, any updates to the GUI should always be carried out on the main thread of the application by calling performSelectorOnMainThread:withObject:waitUntilDone: method. In our example app, the text view update happens on the main thread by calling displayFileStr: method (please look at the code in the project file.)
Synchronous loading can be considered an option only in such cases where we are sure that the execution will hardly take any time or resources. For example, to fetch a string from a URL (let’s say a very small file on a server,) which will help us take one of the alternate paths of code execution. If we use Synchronous loading in this case, we would ensure that even if the file isn’t retrieved (an error happens,) the application will not crash or stall, as it will take the alternate course.

Here is the example project file as a zip for download.

If you haven’t gone through first part, I highly recommend that you go through it.

Part 1 of this series can be viewed here

— §§§ —

 

games and apps developer & producer india | iPhone iPad based game development in Gurgaon Noida Delhi NCR India | mobile apps development india | Xcode iOS trainings and courses in swift for corporates & companies | Indian iOS Games and apps developers | iPhone app and game development courses workshops in swift | iPhone & iPad Application development in India | iPhone development trainings & classes in swift & objective C | iOS trainings for corporates & companies india | Apple development training courses Delhi NCR Gurgaon Noida | iOS games and applications development Delhi NCR Noida Gurgaon India | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon | iPhone & iPad games for eLearning | ios application development in swift objective C India | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India