在 Swift 2.0 单页应用程序项目中,在 XCode 7.0.1 中,使用 Swift 依赖注入框架Swinject,我正在执行以下操作:
复制协议.swift:
protocol DuplicateProtocol { var id: String { get } }
SingletonProtocol.swift:
protocol SingletonProtocol { var id: String { get } }
复制代理.swift
class DuplicateProxy: DuplicateProtocol {
let id: String
init ( id: String ) {
self.id = "DuplicateProxy." + id
}
}
SingletonProxy.swift:
class SingletonProxy: SingletonProtocol {
let id: String
init ( id: String ) {
self.id = "SingletonProxy." + id
}
}
ViewController.swift:
import UIKit
class ViewController: UIViewController
{
var duplicate: DuplicateProtocol?
var singleton: SingletonProtocol?
required init? ( coder aDecoder: NSCoder ) {
print( "ViewController.init?", duplicate, singleton )
super.init( coder: aDecoder )
}
override func viewDidLoad () {
print( "ViewController.viewDidLoad", duplicate, singleton )
super.viewDidLoad()
}
}
AppDelegate.swift:
import Swinject
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application ( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]? ) -> Bool {
let container = Container()
let singleton = SingletonProxy( id: "first" )
container.register( SingletonProtocol.self ) { _ in singleton }
container.register( DuplicateProtocol.self ) { _ in DuplicateProxy( id: "second" ) }
container.registerForStoryboard( ViewController.self ) {
r, c in c.duplicate = r.resolve( DuplicateProtocol.self )
}
print( "AppDelegate.application" )
return true
}
}
这是我不幸得到的控制台日志:
ViewController.init? nil nil
AppDelegate.application
ViewController.viewDidLoad nil nil
尽可能简单地说:我需要做出哪些改变?谢谢你,JBM。