Nillifying UITableView Delegates of VC on Dealloc

One of the most annoying crashes on iOS application is when leaving a screen with a UITableView, removing references to the UIViewController, so the ARC will free the memory, and while doing so, the app crashes with the beautiful “EXC_BAD_ACCESS”.

What seems to be the problem?

The first step when trying to understand an iOS app crash, is using crashlytics, one of the most efficient tools for iOS developer, that shows the line that led to the crash as rather peculiar one:

The deal is rather simple, the UIViewController, that was deallocated, contains a UITableView that its delegate is the UIViewController itself (the UIViewController was declared implementing UITableViewDelegate, obviously). During the removing of the UIViewController, the UITableView is called, however the UIViewController doesn’t exist any more. Thus, referring to a deallocated object causes the sympathetic EXC_BAD_ACCESS error.

To prevent it, the delegate, as well as other references, should be set to nil on the dealloc method:

The sameshould be done in cases of UIScrollView and I would guess in UICollectionView just as well.

Whatsoever, managing the memory is critical for mobile development, and I would suggest not to rely solely on the ARC, as many developers do, and implement the dealloc method to nullify crucial resources, like the example here, or to remove observers etc.

Leave a Reply

Your email address will not be published. Required fields are marked *