Thorny crash: MKMapView and ‘message sent to deallocated instance’

This took a while to debug.

I was getting a crash every time I quit a MapView in my Simulator. It turned out the problem code was this which is used to track the user’s location:

[self.mapView.userLocation addObserver:self  
                            forKeyPath:@"location"  
                               options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)  
			       context:NULL];

The code I thought was taking care of this was here:

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    // other code
}

which wasn’t doing the job.

I needed to do this:

- (void)dealloc
{
    [self.mapView.userLocation removeObserver:self forKeyPath:@"location"]; 
    // other code
}

Having said that Apple have introduced a new method as of iOS 5.0 that does this a lot more simply.

- (void)setUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated;

More here:
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html

and lots of gory SO details here:
http://stackoverflow.com/questions/2473706/how-do-i-zoom-an-mkmapview-to-the-users-current-location-without-cllocationmanag

Leave a Reply

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