How To Maintain Threads In iOS Applications

Posted By : Krishna Dagur | 20-Apr-2020

In this blog post, you'll learn how to maintain threads in iOS applications. Read further to explore. 

 

GCD (Grand Central dispatch queue) is used to manage the concurrent operation in the application which avoids the freezing of our application and to keep it always responsive.

 

There are mainly 3 types of Queue.

 

  1. The Main queue
  2. The global queue
  3. Custom queue

 

  1. Main queue: this queue is having the highest priority in all . all the Ui related threads should be run under this category so that it can easily update the UI and the app will not crash on the user actions.

We can simply use it by 

           :code 


 

        Dispatchqueue.main.async{

// Do any Ui updates here 

}

2. The Global Queue: This queue is mainly divided into four types according to the QoS (quality of service). From highest priority to lowest priority.

  1. User Interactive: it is Having the highest priority. used when work is virtually instantaneous. Similar to the main thread.
  2. UserInitiated: It is having the second-highest priority. used when work is nearly virtually instantaneous .such as few seconds or less.
  3. Default: don't use it usually, 
  4. Utility: it is having less priority, work takes a few seconds to minute. Used for heavy operations.
  5. Background: in this case work take time like a minute or an hour, utility and background operations take a minute to an hour . these are used for heavy operations in order not to block the main thread.

Code :

 

Dispatchqueue.global (qos : .background ) . async{

 

// do any type of heavy operation 

}

3. Custom queue :   Custom Queues are queue that you can create on your own and give what ever QOS  and attribute you want

 

Let myconcurentQueue = DispatchQueue(label:”myconcurrentQueue”,qos: background,attribute: concurrent)

Let myserialqueue = Dispatchqueue(label: “myserialqueue”, qos : .background )


How To Use Queue Together? 
 
Let us say you have to do heavy operations like downloading the image and then display the image in the imageview.

 

Code: 

 

Dispatchqueue.global(qos: .background).async{

Let image = downloadImage from server()

 

Dispatchqueue.main.async{

self.myimageView.image = image

}

 

}


 

 

About Author

Author Image
Krishna Dagur

Krishna is Having the knowledge of swift language & iOS Application Development ,He is self motivated and Hardworking with positive attitude towards his career and life.

Request for Proposal

Name is required

Comment is required

Sending message..