Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - An instance of class ... is being deallocated while key value observing are still registered with it

I have a ViewController (with a MKMapView) which is pushed into, because of the NavigationController. So I have a NavBar with a "back" button. Clicking that back-button, I get an error:

2010-01-11 18:05:35.273 TestApp[147:207] An instance 0x1758f0 of class MKUserLocation is being deallocated while key value observers are still registered with it. Observation info is being leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: ( Context: 0x0, Property: 0x17d600> ) Program received signal: “EXC_BAD_ACCESS”.

I have the viewDidLoad method implemented with an Observer:

- (void)viewDidLoad {
    mapView = (MKMapView*)self.view;
    mapView.delegate = self;
    mapView.mapType = MKMapTypeHybrid;
    mapView.showsUserLocation = YES;

    // ...

    [mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL];
    [super viewDidLoad];

}

My dealloc:

- (void)dealloc {
    [groupId release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

Can anyone tell me what's wrong here? I click the back button in the NavBar and then I come into the dealloc method and then it switches back to the higher ViewController and throws this error.

Thanks a lot in advance & Best Regards.

like image 269
Tim Avatar asked Jan 11 '10 17:01

Tim


1 Answers

You're setting and removing an observer on different objects. You are adding the view controller as an observer of the userLocation in the first code sample, then trying to remove it from the default notification center in the second. To properly remove the observer from userLocation, change your -dealloc method to the following:

- (void)dealloc {
    [groupId release];
    [mapView.userLocation removeObserver:self forKeyPath:@"location"];
    [super dealloc];
}
like image 106
Brad Larson Avatar answered Sep 22 '22 00:09

Brad Larson