我有一个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 self
ViewController拥有对ViewModel的强烈引用。ViewModel持有对闭包的强烈引用。闭包包含对ViewController的弱引用:

VC ---strong---> ViewModel
 ^                    |
 |                   strong
 |                    v
  --------weak-----closure

只要将ViewController取消分配(例如,当您取消分配时,就会发生这种情况),ViewModel也会取消分配。

07-24 09:51
查看更多