WeakSelf in blocks

后端 未结 2 417
谎友^
谎友^ 2021-01-19 18:00

Got a question about weak self , blocks and retain cycle.

By the book i understand we need to use weakself in blocks.. The question is , when ?

for example,

2条回答
  •  感情败类
    2021-01-19 18:36

    You should use weak selfs when there is a possibility of retain cycles.

    Imagine an instance of foo has a strong reference to bar. Now you give bar a block with references to foo's self. Now someone releases foo, but bar has kept the block around. Now foo has a strong reference to bar and bar holds a strong reference to foo in the block. Foo will not be released, and therefore also bar, as bar is holding on to it. But the only thing holding on to bar is the now unused foo. You've got yourself a retain cycle, and the two objects are now floating in memory unable to be reached.

    UIView's animations pose no problem, as the block is called before the animate: method returns, and UIView does not keep the block around.

    ARC will usually warn you whenever it sees the possibility of a retain cycle. But that's not always the case. A good rule of thumb is to use weak selfs whenever you don't know where the block will en up.

    Hope this is a bit of help.

提交回复
热议问题