StatefulViewController
StatefulViewController copied to clipboard
Make view property weak in ViewStateMachine to avoid retain cycle
Hi,
When using ViewStateMachine standalone like the following example, I experienced a retain cycle caused by the fact that ViewStateMachine hold a strong reference on the backed view. Using a weak property fixed the problem.
class StateView: UIView {
private var stateMachine: ViewStateMachine!
private var loadingView: LoadingView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupStateMachine()
}
override init(frame: CGRect) {
super.init(frame: CGRect.zero)
setupStateMachine()
}
private func setupStateMachine() {
stateMachine = ViewStateMachine(view: self) // retain cycle
loadingView = LoadingView(frame: self.bounds)
stateMachine["loading"] = loadingView
}
func startLoading(_ message: String) {
loadingView.label.text = message
stateMachine.transitionToState(.view("loading"), animated: false, completion: nil)
}
....
}