Swift Closures - Capturing self as weak -
i trying resolve closure based strong reference cycle in swift.
in code below, object retained owning view controller. progresshud
uiview
that's retained owning view controller. progresshud
leaked every time completion handler called. when using new closure capture feature, declaring self weak or unowned not resolve memory leak.
object.setcompletionhandler { [weak self] (error) -> void in if(!error){ self?.tableview.reloaddata() } self?.progresshud?.hide(false) }
however, if declare weak var self outside of closure, fixes memory leak, this:
weak var weakself = self object.setcompletionhandler { (error) -> void in if(!error){ weakself?.tableview.reloaddata() } weakself?.progresshud?.hide(false) }
any ideas why not working swift capturing?
if assign closure property of class instance, , closure captures instance referring instance or members, create strong reference cycle between closure , instance. swift uses capture lists break these strong reference cycles. source apple
source sketchytech first, important make clear whole issue concerns closures assigning "a closure property of class instance". keep in mind each rule. rules:
- use weak capture if class instance or property optional
- use unowned if class instance or property non-optional , can never set nil
- "you must ... use in keyword, if omit parameter names, parameter types, , return type"
in answear question there should no retain cycle.
Comments
Post a Comment