How to get if observer is registered in Swift

I want to remove the observer after it starts or when the view has disappeared. Here is the code, but sometimes the observer was already deleted when I want to delete 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; } } 
+7
ios swift
source share
1 answer

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

You can also add the willSet method to the property and run this start / stop code when the state changes.

+10
source share

All Articles