Search code examples
iosdictionarymapkitregion

iOS MapKit crashing through didUpdateUserLocation - baffled


I need some help with an app i'm making using MapKit

I'm struggling with the didUpdateUserLocation: - it keeps randomly crashing the app. When I comment out all of the code it works perfectly but this isn't a suitable situation. I've been fiddling around with it all but still no real success.

Here's my code

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    NSLog(@"update loc");
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 250.0, 250.0);//MKCoordinateRegionMake(userLocation.coordinate, mapView.region.span);
    if (first) {
        region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 250.0, 250.0);
        first = false;
    }
    if (!CLLocationCoordinate2DIsValid(userLocation.coordinate)) {
        //do nothing, invalid regions
        NSLog(@"co-ord fail");
    } else if (region.span.latitudeDelta <= 0.0 || region.span.longitudeDelta <= 0.0) {
        NSLog(@"invalid reg");
    } else {
        [mapView setRegion:region animated:NO];
    }
} 

The app never hits "co-ord fail" or "invalid reg" so I don't really know what the problem is since I set the values myself.

The problem usually occurs when the nib for the Map is closed and it has dealloced the view.

I have seen some other suggestions but haven't been confident about their work. Ideally I'd like to use mapView.region.span so to maintain the zoom levels

Many Thanks, James


Solution

  • The problem usually occurs when the nib for the Map is closed and it has dealloced the view.

       [mapView setRegion:region animated:NO];
    

    Well isn't that your problem then?

    This is why we have dependency inversion patterns like Observer/Listener.

    Instead of fiddling around with the view directly with your CLLocationManager delegate, use NSNotification to alert subscribing views (such as your MapView) that it should update. If the MapView has been dealloced it won't do anything.