弱或无主或无

时间:2018-03-31 09:28:08

标签: swift automatic-ref-counting weak-references unowned-references

我有一个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)?
}

现在,这是否会创建一个强大的参考周期?

如果这会创建一个,那么使用什么 - 弱或无主?

1 个答案:

答案 0 :(得分:2)

这是创建强大的参考周期,因为您使用了weak self

ViewController强烈引用ViewModelViewModel强烈提及闭包。闭包拥有对ViewController

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

只要ViewController被解除分配(例如当您解雇时就会发生这种情况),ViewModel也会被释放。

相关问题