Note that there are some explanatory texts on larger screens.

plurals
  1. POblocks and ARC - copy or crash with release build (caused by optimization level)
    text
    copied!<p>I'm using Xcode 4.3.3 and developing for iOS 5.0+. In development of an ARC iOS application, I've started using blocks as a callback mechanism for asynchronous operations. The app works fine in the simulator and on the device. </p> <p>Then I ran it the profiler for the first time, and it started crashing on me nearly right away - in particular, an EXC_BAD_ACCESS when trying to invoke the first callback block. </p> <p>After a little investigation, it was clear the difference in behavior was because the profiler runs in "Release mode" by default - in particular, with Optimization Level set to "Fastest, Smallest [-Os]" instead of "None [-O0]".</p> <p>For example, the following code (simplified for this question) would crash when trying to execute the callbackBlock: </p> <pre><code>- (void) setCallbackBlock:(void (^)(NSString *input))block { callbackBlock = block; } - (void) invokeCallbackWithInput:(NSString *)input { if (callbackBlock) { callbackBlock(input); } } </code></pre> <p>Debugging into it, calling setCallbackBlock with optimization level set to "None", the incoming block would be an <code>NSStackBlock</code>, and the callbackBlock would become an <code>NSMallocBlock</code>.</p> <p>However, with Optimization Level "Fastest, Smallest", it remained an <code>NSStackBlock</code>.</p> <p>Changing the setter code to use <code>[block copy]</code> fixes the crashing problem (based on <a href="https://stackoverflow.com/questions/10263110/ios-5-blocks-crash-only-with-release-build">iOS 5 blocks crash only with Release Build</a>). </p> <p>However, another related question indicates that this shouldn't be necessary with ARC - block variables are copied to the heap in ARC - <a href="https://stackoverflow.com/questions/11433943/why-does-objective-c-block-still-work-without-copying-it-to-the-heap">Why does Objective-C block still work without copying it to the heap?</a> </p> <p>So my question: What's going on here, and why? (Also, how can both of those answers be correct...?)</p> <p><strong>Edit</strong>: To clarify how callbackBlock is being declared - just above my @implementation where those methods are is this: </p> <pre><code>@interface MyClass () { void (^callbackBlock)(NSString *input); } @end </code></pre>
 

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