Inversion of control
Inversion of control(IoC) is the major principle of software engineering. It refers to any sort of programming style where framework controls the flow of program.
iOS devs often confuse themselves with IoC and DI(Dependency Injection). However, DI is just one implementation of IoC.
UIKit relies heavily on IoC for user events, touch events, view life cycles etc. In the case of UIViewController subclass, UIKit calls the code to notify about the view life cycle.
While consuming frameworks, app code initializes framework, then framework control program flow to produce desired result. This phenomenon is called IoC. This allows app code to focus on business and not to worry about any additional tasks.
A popular implementation of IoC is event-driven programs, async APIs, managing the life cycle of an object. Let's take an example of the UIKit view life cycle. As soon as UIViewController class initializes UIKit calls functions in the following order
App code doesn’t ask UIKit about view changes instead, UIKit notifies about view changes. UIKit says Don’t call us, we’ll call you (Hollywood law). Considering UIKit as 3rd party framework, app code transfer control to UIKit.
We can achieve IoC through various mechanisms such as Service Locator pattern, Factory pattern, and Dependency Injection (DI).
Dependency injection is a pattern we can use to implement IoC, where the control is inverted in setting an object’s dependencies. Connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler/composer rather than by the objects themselves.
Service Locator pattern has a Service locator object which has information about all available services in the app. Upon initialization, a service registers itself with a service locator object. When client sends a request to the service locator object, it performs the task and returns needed value. Client handles control to service locator for performing the task.
Factory pattern composes complex objects behind the scene and return them. With factory pattern client handles control to the factory for creating objects.
That’s all from this blog, next we will learn about DI.
Thanks for reading, Happy coding!!
References