swift2 - Swift assign function to var cause retain cycle? -


i met similar question in swift memory management: storing func in var didn't solve problem.

here class definition:

class test {     var block: (() -> int)?      func returnint() -> int {         return 1     }      deinit {         print("test deinit")     } } 

i tried 2 ways assign value block property , got different result. second approach didn't cause retain circle, quite unexpected:

var t = test() // lead retain cycle // t.block = t.returnint  // thought lead retain cycle didn't t.block = {     return t.returnint() } t = test() 

in opinion, variable t captured block while block property of t, can explain why there isn't retain cycle?

in swift, captured variables captured reference (in apple blocks terminology, captured local variables __block). t inside block shared t outside block; block not hold independent copy of t.

originally, there retain cycle in second case too, block holds reference shared copy of t, , t points first test object, , test object's block property points block. however, when re-assign shared variable t (which visible both inside , outside block), break retain cycle, because t no longer points first test object.


in first case, t captured value, because t evaluated in expression t.returnint rather captured variable in block. reassignment of t outside block later has no effect on block, , not break retain cycle. can think of

t.block = t.returnint  

as kind of like

let tmp = t t.block = {     return tmp.returnint() } 

Comments