Introduction to iOS Project Dependency injection

Source: Internet
Author: User

Dependency Injection (Dependency injection)

依赖注入The biggest feature is that it helps us to develop loosely coupled (loose coupled) , maintainable, testable code and programs. The practice of this principle is well-known interface-oriented , or abstract-oriented programming. It is well known that the idea of programming is embodied in all major languages such as jave ,, C++ PHP and .net medium. Of course, the design pattern is much more extensive than these, iOS of course, no exception. This paper mainly introduces the learning process of my study Dependency Injection and the summary of some learning materials, mainly introduces iOS two big frames Objection and Typhoon . On the Android more popular there are roboguice and Dagger and so on.

What is Dependency injection (Dependency injection)?

依赖注入(Dependency Injection)is a technology that separates behavior from dependencies , simply, it allows the developer to define a method function that relies on various external interactions without the need to encode an instance of how these external interactions are obtained. This decoupling between the various components to obtain clean code, compared to hard-coded dependencies, a component only calls the other components it needs at run time, so when the code runs, it injects the other dependent components it needs through a particular framework or container, and pushes it aggressively.

Dependency Injection is the first Spring and Piconcontainer so forth, and is now a default mainstream model, and extends to the front end such as and Angular.js so on.

1. Reliance

If in Class A , there is an Class B instance, then Class A the pair Class B has a dependency . For example ViewControllerA , using an object in the following class ViewControllerB , we say that ViewControllerA the class ViewControllerB has a dependency on the class.

#import "ViewControllerB.h" @implementation viewcontrollera-(void) buttontapped{    viewcontrollerb *VC = [[ Viewcontrollerb alloc] init];    [Self.navigationcontroller PUSHVIEWCONTROLLER:VC animated:yes];}
 

Looking closely at this code, we will find that there are some problems:

(1). If you want to change ViewControllerB the build mode now, if you need to use initWithOrderid:(NSString * orderid) initialization vc , you need to modify the ViewControllerA code;

(2). If you want to test the ViewControllerB effect of different object pairs ViewControllerA is very difficult, because ViewControllerB 的初始化被写死在了 Viewcontrollera ' in the constructor;

(3). If the [[ViewControllerB alloc] init] process is very slow, it is ViewControllerB also difficult to get rid of the process with an already initialized object Mock .

2. Dependency Injection

It is a way to initialize the dependencies directly in the constructor Hard init , and the disadvantage is that the two classes are not independent enough to be tested easily. We also have another Init way, as follows:

@interface Viewcontrollera ()  @property (nonatomic, readonly) Viewcontrollerb *VCB;  @end  @implementation Viewcontrollera  //VCB is created before Viewcontrollera is created and is passed in as a parameter, and/or the  caller can customize it if they wish.  -(Instancetype) Initwithengine: (Viewcontrollerb *) VcB  {     ...     _VCB = VcB;     return self;  }  @end  

In the above code, we vcB pass the object as a parameter to the constructor. The ViewControllerA object was initialized externally before the constructor method was called vcB . Like this kind of non-self-initiated dependency, and through the outside to pass in the dependency way, we call it 依赖注入 .

Now we find that 1 the two problems above are well solved, and simply say that dependency injection has two main benefits:

    • Decoupling, decoupling the dependencies.

    • Because it is decoupled, it is convenient to do unit tests, especially Mock tests.

So the question is, how to learn dependency injection? iOS about DI Dependency Injection framework is more useful to have two: Objection and Typhoon. Here are a few easy ways to introduce the following two frameworks: Objection and Typhoon What is the difference between these two frameworks? There are advantages to both frameworks:
    1. ObjectionFrame, use more flexible, simple usage. The sample code is as follows:

Property registration:

@class engine, brakes; @interface car:nsobject{     engine *engine;     Brakes *brakes;     BOOL Awake;  

Method Injection:

@implementation Truckobjection_requires (@ "engine", @ "brakes") Objection_initializer (Truckwithmake:model:)// Method Dependency Injection + (Instancetype) Truckwithmake: (NSString *) make model: (NSString *) model {  ...} @end

2. Compared to Typhoon the use of a comparative specification, the first need to create a TyphoonAssembly subclass. The methods and properties that need to be injected need to be written in this unified sub-class, and of course different subclasses can be implemented to accomplish different functions:

@interface middleagesassembly:typhoonassembly-(knight*) basicknight;-(knight*) cavalryman;-(id<quest>) Defaultquest; @end

Attribute injection:

-(Knight *) cavalryman{    return [Typhoondefinition Withclass:[cavalryman class]     configuration:^ ( Typhoondefinition *definition) {    [definition Injectproperty: @selector (Quest) with:[self Defaultquest]];    [Definition Injectproperty: @selector (damselsrescued) with:@ (12)];}];}

Method Injection:

-(Knight *) knightwithmethodinjection{        return [Typhoondefinition withclass:[knight class]     configuration:^ ( Typhoondefinition *definition) {    [definition Injectmethod: @selector (setquest:anddamselsrescued:)         parameters:^ (Typhoonmethod *method) {        [method injectparameterwith:[self defaultquest]];        [Method injectparameterwith:@321];}    ];}];}

3. There are, of course, some hard distinctions that Typhoon have now been supported Swift .

4. Both maintenance time is more than 2 years.

TythoonThe advantages of the official presentation:

1) non-invasive. No macros or XML required.  Uses powerful OBJC runtime instrumentation.2) No Magic strings–supports IDE refactoring, code-completion and Compile-time CHECKING.3) provides full-modularization and encapsulation of configuration details. Let your architecture-a story.4) Dependencies declared in any order.  (The order is makes sense to humans). 5) makes it easy to have multiple configurations of the same base-class or protocol. 6) Supports injection of view controllers and storyboard integration. Supports both initializer and property injection, plus life-cycle management.7) powerful memory management features. Provides pre-configured objects, without the memory overhead of singletons.8) excellent support for circular dependencies.9 ) Lean. Have a very low footprint, so are appropriate for CPUs and memory constrained devices.10) while being feature-packed, Typhoon Weighs-in at just (lines of code in total.11) battle-tested-used on all kinds of appstore-featured apps.

Broadly translated:

1) non-invasive. No macro or XML is required. Use powerful OBJC run-time instruments. 2) No magic string-supports IDE refactoring, completion, and compile-time checking. 3) provides configuration details for full-modularization and encapsulation. Let your architecture tell a story. 4) Any order declared in the dependency relationship. (a meaningful order for humans). 5) It is easy to have multiple configurations of the same base class or protocol. 6) Support for Injection view controller and storyboard integration. It also supports both initializer and attribute injection, as well as life cycle management. 7) Powerful memory management function. Provides preconfigured objects with no single-piece memory overhead. 8) Excellent support for circular dependence. 9) Lean. Very low occupancy, so suitable for CPU and memory constrained devices. 10), powerful, typhoon weighs only 3000 lines of code. 11) battle-hardened for various appstore-featured applications.

There are not many online tutorials for these two frameworks, and some of the more useful information is collected. The main use is to look at official documents, respectively:Objection and Typhoon
 

objc.ioBlog posts Dependency injection and Typhoon original Great God (Graham Lee) articles Dependency Injection, iOS and You do not see regret for a lifetime ^_^

Objectionis a lightweight dependency injection framework, inspired by Guice, Google Wallet is also used by the project. "Dependency Injection" is a design pattern for object-oriented programming to reduce the coupling between code. is usually implemented based on an interface, which means that no new object is required, but the object is obtained through the associated controller. The most popular PHP framework laravel of the 2013 is the typical one.

Suppose you have the following scenario: Viewcontrollera.view has a button, click to push a viewcontrollerb, the simplest way to do this:

-  (void) viewdidload{    [Super Viewdidload];    UIButton *button = [UIButton Buttonwithtype:uibuttontypesystem];    Button.frame = CGRectMake (+, +, +);    [Button settitle:@ "button" forstate:uicontrolstatenormal];    [Button addtarget:self action: @selector (buttontapped) forcontrolevents:uicontroleventtouchupinside];    [Self.view Addsubview:button];} -(void) buttontapped{    viewcontrollerb *VC = [[Viewcontrollerb alloc] init];    [Self.navigationcontroller PUSHVIEWCONTROLLER:VC animated:yes];}
 

One of the problems with this writing is that the ViewControllerA need import ViewControllerB , that is, depends on the ViewControllerB production. The more things you rely on, the more troublesome it is to maintain, and the problem of cyclic dependence that objection can be dealt with.

This is accomplished by defining a protocol (protocol) and then registering the class of the Protocol with objection, which can be used to obtain the object corresponding to the protocol. There is no need for the user to care about which class to use, anyway, there are methods and properties (specified in the protocol). This removes the dependency on a particular class. That is what is commonly referred to as "interface-oriented programming".

Jsobjectioninjector *injector = [Jsobjection defaultinjector]; [1]uiviewcontroller <ViewControllerAProtocol> *VC = [Injector getObject: @protocol (Viewcontrolleraprotocol)] ; [2]vc.backgroundcolor = [Uicolor Lightgraycolor]; [3]uinavigationcontroller *NC = [[Uinavigationcontroller alloc] INITWITHROOTVIEWCONTROLLER:VC]; Self.window.rootViewController = NC;

    • [1] Get the default injector , this injector has already been registered ViewControllerAProtocol .
    • [2] gets ViewControllerAProtocol the corresponding Object .
    • [3] VC after getting it, set some of its properties, such as here backgroundColor , because ViewControllerAProtocol there is a definition of this property, so there is no warning .

You can see there are no references here ViewControllerA . Again to see ViewControllerAProtocol how this is registered to injector the, here is related to Module Protocol the registration is Module done in the. Modulejust inherit JSObjectionModule this Class .

@interface viewcontrolleramodule:jsobjectionmodule@end@implementation viewcontrolleramodule+ (void) load{    Jsobjectioninjector *injector = [jsobjection defaultinjector];     INJECTOR = injector? : [Jsobjection createinjector];     INJECTOR = [Injector Withmodule:[[viewcontrolleramodule alloc] init]];     [Jsobjection Setdefaultinjector:injector]; }-(void) configure{    [Self Bindclass:[viewcontrollera class] Toprotocol: @protocol (Viewcontrolleraprotocol)];} @end

The bind operation is configure done in the method, which is automatically triggered when it is added to the process injector .

Jsobjectioninjector *injector = [Jsobjection defaultinjector]; [1]injector = injector? : [Jsobjection Createinjector]; [2]injector = [injector Withmodule:[[viewcontrolleramodule alloc] init]]; [3][jsobjection Setdefaultinjector:injector]; [4]

    • [1] Gets the defaultinjector
    • [2] If the default injector does not exist, create a new
    • [3] injector register for us in thisModule
    • [4] Set this injector to the defaultinjector

This code can be placed directly + (void)load in the execution, so that you can avoid AppDelegate the import various Module .

Because we cannot get the corresponding directly Class , we must define the methods and properties of external exposure in the protocol, and then we should Class implement the Protocol as well.

@protocol viewcontrolleraprotocol <NSObject> @property (nonatomic) Nsuinteger currentindex @property (nonatomic ) Uicolor *backgroundcolor, @end @interface viewcontrollera:uiviewcontroller <ViewControllerAProtocol> @end

Through the Objection implementation of dependency injection, it will be better to achieve SRP(Single Responsibility Principle) , the code is more concise, more comfortable mood, better life.

Overall, this lib is quite reliable, has been maintained for more than two years, there are some projects in use, to improve the efficiency of development members will also have a lot of help, you can consider trying .

Introduction to iOS Project Dependency injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.