假设我们有一个UITableViewController
that ondidSelectRowAtSection
加载一个名为 ie: 的类的实例,ClassToInject
并且它想通过属性注入来注入它,因为我们ViewControllerToBePushed
有一个 , 的属性ClassToInject
,随后(因为它是一个UITabBarViewController
)在didSet
回调中搜索它的所有viewControllers
属性符合ClassToInjectPresentable
简单的:
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)
}
}