Note that there are some explanatory texts on larger screens.

plurals
  1. PORetaining mutable variables in blocks without causing retain cycles in Objective-C
    primarykey
    data
    text
    <p>I'm using blocks to handle the response of async http requests in a non-ARC project. The code looks like this (the relevant parts):</p> <pre><code>NSMutableUrlRequest* request = ...; __block typeof(self) mutableSelf = self; void (^didGetSessionBlock)(Gopher* newGopher) = ^(Gopher* newGopher) { if (newGopher.statusCode == HTTP_OK) { ... mutableSelf.retryOnFail = NO; [mutableSelf executeRequest:request]; } ... [mutableSelf setStatusCode:newGopher.statusCode]; }; Gopher* newGopher = [[[Gopher alloc] init] autorelease]; [newGopher setDidCompleteBlock:didGetSessionBlock]; [newGopher fetchSession:myApp.settings.userName password:myApp.settings.password]; </code></pre> <p><code>__block mutableSelf</code> is used so that I can modify <code>self</code> inside of the block (and not a copy of <code>self</code>). The <code>__block</code> keyword, if I understand correctly, also has the effect that <code>mutableSelf</code> is not retained so it might already be released when the block is executing (and this is exactly what happens).</p> <p>If I change </p> <pre><code>[mutableSelf executeRequest:request]; </code></pre> <p>to </p> <pre><code>[self executeRequest:request]; </code></pre> <p>all is well since <code>self</code> gets retained and won't be released until the block has executed. However, directly referencing self might cause leaks due to retain cycles.</p> <p>Is there a way around this? Should I manually retain <code>mutableSelf</code> when it's declared and then release it inside of the block? Or should I use <code>self</code> inside the block where I'm not modifying it, potentially creating a leak? Both variants seem fragile and need explanations in comments to avoid confusion and future bugs if/when the code is modified.</p> <p>Is there a way to solve this problem? If not, what is the best approach?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload