Let say, I have the code below
self.customObj = self.assembly.customObj() as? NSObject
let temp3 = self.assembly.customObj() as NSObject
If I use TyphoonScopeObjectGraph
for customObj
, it should return the same instance.
But when I debug, the customObj
properties are not the same as shown:
As far as I understand, customObj
and temp3
should be the same instance. But as you see in the image, customObj
and temp3
have the same ObjectiveC.NSObject
address but all of its properties (_shortFormatter
, _longFormatter
) have different address. What happen? How we can get the same instance for customObj
and temp3
. An example is very helpful.
Thanks.
You can get the project source code from here
In the example above if you want self.customObj
and temp3
to be the same instance, then you need either TyphoonScopeSingleton
or TyphoonScopeWeakSingleton
.
The way TyphoonScopeObjectGraph
works is that during resolution if two instances declare that they depend on another component called context
, then the same shared instance of context
will be returned. However these are not retained by Typhoon. So you can load a whole object graph (eg a view controller, along with dependencies) and then discard it when done, rather than use singletons, as you might otherwise. TyphoonScopeObjectGraph
is also useful for having circular dependencies, such a a controller and view, that has a delegate property pointing back to the controller.
It helps to explain with an example: Let's say we have:
@interface MyViewController : UIViewController
@property(nonatomic, strong, readonly) InjectedClass(ShoppingCart) cart;
@property(nonatomic, strong) InjectedClass(MyView) view;
@end
@interface MyView : UIViewController
@property(nonatomic, strong, readonly) InjectedClass(ShoppingCart) cart;
@end
//ShoppingCart has object-graph scope
@interface ShoppingCart
@end
Now if we ask Typhoon to give us an instance of of MyViewController
, then a controller will be returned where both MyViewController
and MyView
will have the same instance of ShoppingCart
ShoppingCart
. . so you see TyphoonScopeObjectGraph
loads an object graph with shared instances, but allows that whole object graph to be discarded after the use-case.