Retain Cycles and Blocks

When using blocks, be wary of the creation of retain cycles. It is very easy to unintentionally retain self inside a block. This occurs by referencing self directly or by using an ivar, which captures self indirectly.

To avoid the retain cycle, capture a weak variant of self and then assign the weak reference to a strong reference prior to use within the block. Adding the strong reference at the very start of the block ensures that if a strong reference is possible, it endures throughout the entire block scope. Don’t forget to check that the strong reference to self is not nil. The following listing avoids issues with retain cycles and nil references:

__weak TestBedViewController *weakSelf ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.