Sunday, April 15, 2012

Blocks don't retain variables


I recently had user reports of The Rebus Show crashing in iOS 5.1. The app had been tested and even put through a beta program. The intermittent crash happened because the blocks don't retain variables, in this case myObj was intermittently released by iOS:

    runBlockAfterDelay(delay, ^{
        [myObj myMethod];
        myObj = nil;
    });

The fix was simple:

    __block MyObj* temp = myObj;
    runBlockAfterDelay(delay, ^{
        [temp myMethod];
        temp = nil;
    });

Tracking down this issue was difficult because it was intermittent, crash reports didn't symbolicate this code, ARC was responsible for the object's release, and because the crash manifested itself in an apparently unrelated event handler myMethod was responsible for removing. Fortunately, I noticed the event handler's owner address was different than the current object's address.

No comments:

Post a Comment