WeakSelf in blocks

后端 未结 2 416
谎友^
谎友^ 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:45

    As others have pointed out, you should definitely use the weakSelf pattern in situations where you would otherwise have strong reference cycles (aka, retain cycles). But more generally, you should use weakSelf whenever you don't want the block to retain the object itself (even in cases where there is no retain cycle involved).

    A wonderful example would be a network operation that is initiated by some view controller. Let's say the user initiates some upload. The question is whether you want the asynchronous upload process to retain the view controller even though it might have a reference to that view controller to update some progress bar or the like. You may well not want it to retain the view controller if the view controller is dismissed, even though you might want to let the upload continue.

    This is just a random example, but bottom line, you might want to use weakSelf pattern whenever you want the background process to continue, but you don't want it retaining the other object. Just look at your functional needs and consider the strong reference cycle risks, and make the decision whether you need to employ the weakSelf pattern or not.

    In the case of animateWithDuration, the animation stops when the view is dismissed and the strong reference is immediately resolved, so there is no strong reference cycle.

提交回复
热议问题