EDIT: changed the title. I didn't know it at the time but this is a duplicate of Why am I crashing after MKMapView is freed if I'm no longer using it?
This question is similar to Why is object not dealloc'ed when using ARC + NSZombieEnabled but different enough that I thought it worth throwing out there in case anyone understands and can explain to me what is happening. The other question may be an XCode bug so I presume this could be similar.
Scenario:
RootViewController
has atableView
displaying a bunch of items- Selecting a cell presents a modal
detailViewController
containing anothertableView
- One of the table cells in
detailViewController
contains anMKMapView
showing the location of the item mapView.delegate = detailViewController
- Dismiss the modal
detailViewController
Soon after this, the app crashes b/c the MKMapView
sends mapView:viewForAnnotation:
to the now dealloc'ed detailViewController
. This crash repro'ed on a users device with an ad-hoc distribution build so the issue has nothing to do with NSZombieEnabled
.
I was able to resolve the crash by adding:
_mapView.delegate = nil;
to the dealloc
method of the tableViewCell
containing the mapView.
QUESTION: why is it necessary to nil the delegate when the cell is dealloc'ed? It seems like the mapView
should be dealloc'ed by ARC when the cell is dealloc'ed leaving this unnecessary. It is good practice to nil delegates but I didn't think it would be required in this case.
EDIT: all subviews of both detailViewController
and the UITableViewCells
are declared as (nonatomic, strong)
properties ala:
@property (nonatomic, strong) MKMapView * mapView;
EDIT 2: Guess I need to get better at reading the docs. @fluchtpunkt is correct. Here's the relevant info from the MKMapView
documentation:
Before releasing an MKMapView object for which you have set a delegate, remember to set that object’s delegate property to nil. One place you can do this is in the dealloc method where you dispose of the map view.
detailViewController
, especially theMKMapView
? – AweUITableViewCell
as a strong property. – Timeserver