When a request is sent from a viewcontroller having a completion handler in place, but before the request can be received by the device, we go back to the previous view. What will happen to that completion handler block?
-
3Show example code please. – matt Jan 06 '19 at 18:50
2 Answers
This case is the reason why we need to put [Weak self]
in completion , to avoid strong references to that vc and so to be deallocated , if you skipped it , then what you did in completion will run but you'll not see anything as the vc's view is hidden after the pop while this instance is still in memory and will cause memory drains by time

- 98,760
- 8
- 65
- 87
When are objects deallocated from memory?
Is it when the related object is moved away from the screen? Wrong!
Or is it When the related object is removed from memory? Right!
All objects are removed from memory when 'there is nothing left to strongly point to them'. This could happen when the view goes offscreen. See AutomaticReferenceCounting from docs.
Closures or completionHandlers, point to the instance. Hence they will hold the instance in memory. The instance itself will also point to the completionHandler. So both would be waiting for the other to be removed from memory. As if two people each say I would like you exit the house first. Ending result is that that none of them leave.
You need to avoid that from happening. As Sh_Khan said you do that with [weak self]
. For more on why we do that. See Reference to property in closure requires explicit 'self.' to make capture semantics explicit

- 33,269
- 19
- 164
- 293
-
A reference cycle will only be created if the view retains a strong reference to the closure as well as the closure referencing self. – Dale Jan 07 '19 at 02:30