Reputation:
I need to add a viewcontroller as a subview of mt current view, but cannot deinit after I don't need it anymore
let viewController = CountrySelectViewController()
viewController.view.frame = self.view.bounds
viewController.view.alpha=0
self.view.addSubview(viewController.view)
UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
viewController.view.alpha=1
}, completion: { (finished: Bool) in
})
viewController.completionHandlerClose = {
UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
viewController.view.alpha=0
}, completion: { (finished: Bool) in
viewController.view.removeFromSuperview()
viewController.view = nil
})
}
Upvotes: 0
Views: 302
Reputation: 130210
There is an obvious strong reference cycle that has to be broken using weak
references:
viewController.completionHandlerClose = { [weak viewController] in
guard let controller = viewController else { return }
UIView.animate(
withDuration: 0.25,
delay: 0.0,
options: [],
animations: {
controller.view.alpha = 0
},
completion: { _ in
controller.view.removeFromSuperview()
controller.view = nil
}
)
}
See https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html
Upvotes: 1