Typically, dependency injection is used to create a fully formed object, saying, "instead of asking for this object, here you go, use this." But in this case, we want to create an instance of a new object. So instead of entering an object, all we need to do is enter a class. "Instead of creating a specific class, here you go, create one of them."
There are two main forms of dependency injection: “constructor injection” (I will stick with the term “constructor”, although Objective-C divides this into distribution and initialization) and “property injection”.
To inject a constructor, specify the class in the initializer:
- (instancetype)initWithFooBuilderClass:(Class)fooBuilderClass;
To inject properties, specify the class in the property:
@property (nonatomic, strong) Class fooBuilderClass;
The constructor input is clearer because it makes the dependency obvious. But you may prefer nesting properties. Sometimes I start one path and refactor in relation to another, changing my mind.
In either case, you can have a default initializer that either calls -initWithFooBuilderClass: or sets the property to [FooBuilderClass class] .
Then doSomething will start as follows:
- (void)doSomething { id foo = [[self.fooBuilderClass alloc] init]; ...
source share