0

Most of the articles I've read explain when and why to capture a weak self inside a closure in Swift or bloc in Objc to avoid retain cycles. But I'm having a hard time figuring out when you shouldn't do this inside a closure.

Since you shouldn't always capture self weakly, when should you keep a strong reference to self inside a closure?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
alexisSchreier
  • 677
  • 1
  • 5
  • 21
  • 1
    when u don't hold a strong reference to closure/block itself, you can pass strong self to closure. Deadlock happens only if self holds a strong reference to block and block holds a strong reference to self. If in any case this link breaks u can pass self as a strong reference and u won't have any memory leak issue. Example passing self to `UIView.animate` but this isn't recommended because though u might not enter into memory leak u might have its view deallocated and u might end up accessing view components that no longer exists :) – Sandeep Bhandari Apr 30 '19 at 09:07
  • @SandeepBhandari why dispatch queue are not affected by reference counting? – Jarvis The Avenger Apr 30 '19 at 09:14
  • 1
    @dahiya_boy never? What kind of nonsense is this? If never would be appropriate, why would you think apple added capture lists in the first place? – J. Doe Apr 30 '19 at 09:20
  • 1
    One such case where you can add strong reference of self is lazy property: You can use self inside the closure of a lazy property. It will not cause any retain cycles. The reason is that the immediately applied closure {}() is considered @noescape. It does not retain the captured self. – Jarvis The Avenger Apr 30 '19 at 09:22
  • @jarvis-the-avenger: I made a mistake dispatch queues are reference counted objects but retain/release calls on these queues are ignored by iOS as they are global to apps. Quote from Apple docs : "because they are global to your application, retain and release calls for these queues are ignored." So holding strong reference to these queue instances should not alter the ARC of the queue itself. Hence I deleted my second comment – Sandeep Bhandari Apr 30 '19 at 09:27
  • @SandeepBhandari That's correct!!! – Jarvis The Avenger Apr 30 '19 at 09:28

0 Answers0