我有一个 ViewController 类,如下所示:
class ViewController {
var viewModel = ViewModel()
viewDidLoad() {
self.viewModel.showAlert = { [weak self] in
self?.alert()
}
}
func alert() {
// alert logic
}
}
这是 ViewModel 类
class ViewModel {
var showAlert: (() -> Void)?
}
现在,这是否会创建一个强大的引用循环?
如果这创建了一个,那么使用什么 - weak 还是 unowned?
最佳答案
这不会创建一个强引用循环,因为您使用了weak self
。
ViewController
持有对 ViewModel
的强引用。 ViewModel
持有对闭包的强引用。闭包包含对 ViewController
的弱引用:
VC ---strong---> ViewModel
^ |
| strong
| v
--------weak-----closure
只要 ViewController
被释放(例如,当您关闭它时就会发生这种情况),ViewModel
也会被释放。
关于swift - 弱或无主或无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49586264/