7

Tôi có một ViewController (với một MKMapView) được đẩy vào, vì NavigationController. Vì vậy, tôi có một NavBar với một nút "trở lại". Nhấp rằng back-nút, tôi nhận được một lỗi:iPhone - Một thể hiện của lớp ... đang được deallocated trong khi quan trọng giá trị quan sát vẫn được đăng ký với nó

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”.

Tôi đã phương pháp viewDidLoad thực hiện với một 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]; 

}

dealloc của tôi:

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

Có ai cho tôi biết có gì sai ở đây không? Tôi bấm vào nút quay lại trong NavBar và sau đó tôi đi vào phương pháp dealloc và sau đó nó chuyển trở lại ViewController cao hơn và ném lỗi này.

Cảm ơn rất nhiều trước & Trân trọng.

Trả lời

12

Bạn đang đặt và xóa người quan sát trên các đối tượng khác nhau. Bạn đang thêm bộ điều khiển xem làm người quan sát của userLocation trong mẫu mã đầu tiên, sau đó cố gắng loại bỏ nó khỏi trung tâm thông báo mặc định trong lần thứ hai. Để xóa đúng người quan sát khỏi userLocation, hãy thay đổi phương thức -dealloc của bạn thành:

- (void)dealloc { 
    [groupId release]; 
    [mapView.userLocation removeObserver:self forKeyPath:@"location"]; 
    [super dealloc]; 
} 
+0

công trình này tuyệt vời! không còn lỗi nữa. – Tim

+0

Cụ thể hơn, bạn đã kết hợp hai mô hình thông báo khác nhau: NSNotifications và KVO. (Mặc dù giải pháp của Brad là chính xác!) –