Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get if an observer is registered in Swift

Tags:

ios

swift

I want to remove an observer after it run or when the view dissapeared. Here is the code but sometimes the observer was already removed when i want to remove it again. How to check if it is still registered?

 override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if(!didOnce){
        if(keyPath == "myLocation"){
            location = mapView.myLocation.coordinate;

            self.mapView.animateToLocation(self.location!);
            self.mapView.animateToZoom(15);
            didOnce = true;
            self.mapView.removeObserver(self, forKeyPath: "myLocation");
        }
    }
}
override func viewDidAppear(animated: Bool) {
    didOnce = false;
}
override func viewWillDisappear(animated: Bool) {
    if(!didOnce){

        self.mapView.removeObserver(self, forKeyPath: "myLocation");
        didOnce = true;
    }
}
like image 653
MegaX Avatar asked Apr 11 '15 12:04

MegaX


1 Answers

You're on the right track. Add an isObserving property to your class. Set it to true when you start observing, and set it to false when you stop observing. In all cases check the flag before starting/stopping observing to make sure you are not already in that state.

You can also add a willSet method to the property and have that code start/stop observing when the property changes states.

like image 83
Duncan C Avatar answered Nov 15 '22 19:11

Duncan C