Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency Injection in iOS Apps

Dependency Injection in iOS Apps

yashigani

April 26, 2016
Tweet

More Decks by yashigani

Other Decks in Programming

Transcript

  1. • Depend interface, not depend implementations • Make less dependency

    between components • Improve testability • Make easy to mock dependency objects
  2. • Pros • Easy to control • Cons • Don’t

    fit storyboard • Need dependency objects to create
  3. // Property injection override func prepareForSegue() { if let vc

    = segue.dVC as? NextViewController { vc.client = client } }
  4. • Pros • Don’t need to dependency objects to create

    • Fit view controller with storyboard • Cons • Too difficult to stay simple • Overtime pass to dependency objects
  5. // Hold all dependency objects in app class Context {

    // Singleton!!! private static let context = Context() static func get() -> Context { return context } let client = APIClient() } class ViewController: UIViewController { // Depend to singleton pattern let context = Context.get() }
  6. // protocol for Context protocol ContextType { var client: APIClientType

    { get } } class Context: ContextType { private static let context = Context() static func get() -> Context { return context } let client: APIClientType = APIClient() }
  7. protocol WithContext { var context: ContextType { get } }

    extension WithContext { var context: ContextType { return Context.get() } } class ViewController: UIViewController, WithContext {}
  8. • Default behavior, WithContext return static Context object • In

    unit test, add extension ViewController.context • Change context object to mock • Easy to mock context because it depend to ContextType • Solve strong dependency to singleton pattern
  9. • Don’t depend to implementations, depend to protocols • DI

    makes easy and flexible to inject dependency objects • Depending protocols makes easy to change implementations • Fit View Controller with storyboard very much ✨