StoryboardInitCompleted块完成时,SwinjectStoryboard解析nil
对象。这就是为什么ViewController中的viewModel: ViewModelProtocol!
对象为nil的原因,它使我的应用程序始终在Swift 4.2中崩溃。
MainContainer:
import Swinject
class MainContainer {
static let sharedContainer = MainContainer()
let container = Container()
private init() {
setupContainers()
}
private func setupContainers() {
Container.loggingFunction = nil
container.register(UnsplashService.self){ _ in UnsplashService()}.inObjectScope(.container)
container.register(UnsplashManagerProtocol.self){ r in UnsplashDataFetcher(with: r.resolve(UnsplashService.self)!)}.inObjectScope(.container)
container.register(ViewModelProtocol.self){ r in ViewModel(withClient: r.resolve(UnsplashManagerProtocol.self)!)}.inObjectScope(.container)
}
}
SwinjectStoryboard:
import Swinject
import SwinjectStoryboard
extension SwinjectStoryboard {
@objc class func setup() {
let mainContainer = MainContainer.sharedContainer.container
defaultContainer.storyboardInitCompleted(PhotosCollectionViewController.self) { _, controller in
controller.viewModel = mainContainer.resolve(ViewModelProtocol.self)!
}
}
}
PhotosCollectionViewController:
class PhotosCollectionViewController: UICollectionViewController {
var viewModel: ViewModelProtocol!
...
}