Multi Threading in iOS
Adnan Ahmed
Consultant | Lead Mobile App Developer | iOS (Objective-C, Swift) | Flutter | FinTech Solutions | XMPP | VOIP | CI/CD | TDD Advocate
Multi threaded is an ability of Processor to execute multiple processes or thread concurrently supported by Operating System.
A Program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources.
Threading has a real cost in sense of memory and performance, each thread required memory allocation in both Kernel and your program memory space.
Multi threading was introduced in iOS 3.2, we have three options for multi threading in iOS which is given below with basic details:
1) NSOperationQueue:
NSPerationQueue written in Objective C and suitable for complex operations you want to run concurrently. It allows for subclassing, arbitrarily complex dependency graphs, cancellation and a supports a number of other higher-level semantics. NSOperationQueus uses GCD under the cover.
NSOperationQueue can be more suitable for long-running operations that may need to be cancelled or have complex dependencies. It has some more fancy feature as compared to GCD.
2) Grand Central Dispatch:
It is an API written in C Language. GCD is best when you want to perform simple task in background and setup tasks so much as simply "do basic stuff in parallel". You can't interact the tread during execution, when you en-queue a block in a GCD dispatch queue, it will definitely be executed at some point.
GCD dispatch queues are better for short tasks that should have minimum performance and memory overhead.
3) NSThread:
NSThread grant you direct and full control over thread you created e.g when you are interfacing some other subsystems that consumes thread object directly and you need to be on same page with it.
Which option you need to use in your program is totally dependent on circumstances and scenario you are in right now.
Happy Coding!