swift retain cycle in function -


i'd ask if retain cycle happens in situation:

func somefunc() {     var avar = someobj()     funcwithclosure(something, completionhandler: { _ -> void in         avar = someobj() // new     }) } 

in case, refer avar closure. wonder if creates retain cycle. if true, should fix by:

func somefunc() {     var avar = someobj()     funcwithclosure(something, completionhandler: { [weak avar] _ -> void in         avar = someobj() // new     }) } 

just expand on question, would retain cycle if avar references closure. example:

func somefunc() {     var avar = someobj()     avar.funcwithclosure(something, completionhandler: {         dosomethingwith(avar)     } } 

avar references closure because calls function, , closure references avar because uses variable in body. break cycle, create weak reference avar outside closure, this:

func somefunc() {     var avar = someobj()     weak var weakvar = avar     avar.funcwithclosure(something, completionhandler: {         if let var = weakvar {              dosomethingwith(var)         }     } } 

weakvar references avar, use in place of avar. , references weakly, when avar goes out of scope (when function completes), ref count can become zero. inside closure, since weakvar weak var, need unwrap somehow before using.

in question, proposed adding [weak avar] closure's capture list, don't believe work.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -