Search code examples
objective-cobjective-c-blocks

Should I use weakSelf in private convenience methods when they are called by block?


The title almost covers it. I understand why use weakSelf inside blocks.

But imagine a situation where we have a view controller. The view controller calls a data API (a singleton shared instance) which has a completion block. So in this call VC provides a completion block to which the VC doesn't hold a reference. There is also a private convenience method inside VC which does something to a UI component and calls self. But this private convenience method is called inside the block.

So knowing that, should I use weakSelf in the convenience method too?


Solution

  • One would use weakSelf pattern wherever:

    • You would otherwise have a strong reference cycle;

    • You are using cancelable asynchronous tasks and wish to cancel them in dealloc; or

    • If the view controller is dismissed while the asynchronous call is still underway, you do not want it retained for the duration of the asynchronous call.

    This latter point means that one may use weakSelf pattern in conjunction with completion blocks for asynchronous methods, regardless of whether there is a strong reference cycle or not. The question is simply whether you need the view controller retained for the duration of the asynchronous call even if the view controller has since been dismissed.