Apple ❤ Zombies

or How I learned to stop worrying about EXC_BAD_ACCESS and work around Apple’s bug.

Daniel Spinosa
Engineering in a startup
2 min readNov 7, 2013

--

When your app crashes, it’s your fault. Normally that means you did something dumb. But sometimes it means Apple did something dumb and you forgot to work around it. That happens to be the case with UIScrollView’s delegate and me.

The situation was all too familiar: occasional crash reports without useful stack information providing no help reproducing or fixing the crash. Fortunatley, I stepped in shit while debugging something else and could reproduce the EXC_BAD_ACCESS on command.

Zombies, like farts, are often silent but deadly. Thankfully Xcode has NSZombieEnabled to help clear the air.

Turning on NSZombieEnabled made it obvious: the delegate of my scroll view was being sent a message from the scroll view after it was deallocated. This is, of course, impossible with ARC; weak refernces to the delegate are set to nil when the delegate is deallocated. Only, it was possible. I was watching it happen.

Somewhere in the depths of the framework, Apple is holding an __unsafe_unretained reference to the delegate. Those don’t get set to nil when the object is deallocated, hence the unsafe part. The delegate property of UIScrollView is certainly weak, or this would blow up all the time. So, where is the problem? I don’t know for sure, but I have some idea where this pointer is dangling…

Dan: 1 — Zombies: 1 (a tie goes to the coder) https://github.com/spinosa/DSZombieScroll

Calling [someScrollView setContentOffset:offset animated:YES] and then immediately deallocating the delegate (ie. before the animation is complete) produces the crash. To see it in action for yourself, check out my little example: DSZombieScroll. It seems that Apple hangs on to the __unsafe_unretained pointer during the animation.

The workaround depends on your situation,but it’s probably simple. For my fix in the Shelby codebase, I just rearranged the order of deallocation.

My relationship status with Apple remains love/hate. Which is usually a pretty big number.

Radar # 15403528

Dan ♥ XKCD

--

--