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]
2. Java and dependency injection frameworks. You can use dependency injection without any additional framework by providing classes with sufficient constructors or getter and setter methods. A dependency injection framework simplifies the initialization of the classes with the correct objects.
Dependency Injection is a software design pattern in which an object receives other instances that it depends on. It's a commonly used technique that allows reusing code, insert mocked data, and simplify testing. An example could be initializing a view with the network provider as a dependency.
Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.
I'm beginning my evaluation of an Objective-C DI framework called Objection. It's inspired by Google Guice for Java.
@class Engine, Brakes;
@interface Car : NSObject
{
Engine *engine;
Brakes *brakes;
BOOL awake;
}
// Will be filled in by objection
@property(nonatomic, retain) Engine *engine;
// Will be filled in by objection
@property(nonatomic, retain) Brakes *brakes;
@property(nonatomic) BOOL awake;
@implementation Car
objection_register(Car)
objection_requires(@"engine", @"brakes")
@synthesize engine, brakes, awake;
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With