O'Reilly logo

The Core iOS Developer’s Cookbook, Fifth Edition by Rich Wardwell, Erica Sadun

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required