This is probably a fundamental question for an experienced iOS developer, but coming from a Java background where we have lots of Dependency Injection (DI) goodies (i.e., Spring) I’m having some trouble figuring out who should own the DI objects. Unfortunately, I find myself creating a bunch of Singletons which is becoming pretty nasty to manage.
For instance, we have some Configuration that other classes would like access to. Currently we just have a singleton instance for Configuration, which makes testing a bit difficult. Technically, we overcome this problem using method swizzling in OCMock.
In Java/Spring, there’s some container that creates/owns these objects. In iOS, I think the closest things I have to a container are UIApplication and UIApplicationDelegate. Does it make sense for these things to create/own these objects that will ultimately get injected into other objects?
If so, what is an appropriate strategy to access these objects? For instance, create a category on UIApplication or UIApplicationDelegate to access these objects like:
[[UIApplication sharedApplication] configuration] or [[[UIApplication sharedApplication] delegate] configuration]
Indeed DI doesn’t seem to be something that people normally use in iOS, like we do in Java or C#.
Personally, i tend to create my own singleton called Application, that holds all the services and information for the application. This way I get the simplicity of a simple singleton, without being attached to iOS specifically (even though obj-c can’t really be used almost anywhere else). So in my apps I usually have:
So the only class that needs to be a singleton is the Application one (unrelated to UIApplication), and it creates all the services in the init method.