讓我們假設我們有一個UITableViewController
上didSelectRowAtSection
加載一個類的實例,即命名爲:ClassToInject
,並希望通過物業注入注入,因爲我們ViewControllerToBePushed
有ClassToInject
的屬性,即隨後在didSet
回調(因爲它是一個UITabBarViewController
),它搜索符合ClassToInjectPresentable
簡單,因爲它所有的財產viewControllers
:Swinject注入自身的財產到新的UIViewController
protocol ClassToInjectPresentable {
var property: ClassToInject { get set }
}
到現在爲止,我只想做這樣的事情:
func didSelectRowAtIndexPath {
let classToInject = self.loadClassToInjectFor(indexPath)
let tabBarViewController = SomeTabBarViewController()
tabBarViewController.property = classToInject
self.navigationController.push(tabBarViewController, animated: true)
}
而且在SomeTabBarViewController
...
class SomeTabBarViewController: ClassToInjectPresentable {
var property: ClassToInject? {
didSet(newValue) {
self.viewControllers.filter{ $0 is ClassToInjectPresentable }.map{ $0 as! ClassToInjectPresentable }.forEach{ $0.property = newValue }
}
}
,一切都應該得到加載好和容易(但它不是)。我已閱讀Swinject
,這可能會解決它。我見過很多例子註冊了諸如:
container.register(Animal.self) { _ in Cat(name: "Mimi") }
但我不知道我是否可以註冊在self
加載某些屬性:
container.register(ClassToInjectInjector.self) { _ in
self.loadClassToInjectFor(indexPath) }
// And then
container.register(ClassToInjectPresentable.self) { _ in
SomeTabBarViewController() }
.initCompleted { r, p in
let tabBar = p as! SomeTabBarViewController
tabBar.property = r.resolve(ClassToInjectInjector.self)
// And lastly?
self.navigationController.pushViewController(tabBar, animated: true)
}
}
'tabBar.property = injector'從哪裏來? –
對不起,它的意思是'tabBar.property = property'。我已經更新了一個答案 –