This blog entry shows how to use snippets in Xcode to avoid retain cycles when working with asynchronous blocks. We use the weakSelf and strongSelf paradigm that Apple’s engineers recommend as a best practice in Objective-C.

Why weakSelf And strongSelf?

 
Nowadays a great many apps perform asynchronous operations using GCD blocks. For example, if you’ve ever done a fetch over a network you may have used asynchronous AFNetworking callback blocks or Apple’s native session-based asynchronous blocks. Apple recommends using a weak variable to reference self whenever we perform asynchronous operations in order to prevent retain cycles. Okay…but why?

First, some background. Remember that a block captures variables within its scope along with their qualifiers. That means if we reference self inside a block (i.e., a variable that’s intrinsically __strong), the block will hold onto it strongly. Similarly, if we reference a __weak variable in a block, the block will capture the weak variable, uh, weakly. 🙂

Continue reading »