Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Observer (KVO): Checking for Existence

I have a box that the user is able to pan around. For that, I add an observer to check if it's center has changed:

self.boxView!.addObserver(self, forKeyPath: "center", options: .old, context: &BoxCenterContext)

This gets added after an animation that presents the box.

When the box dismisses, I remove it as this:

self.boxView!.removeObserver(self, forKeyPath: "center", context: &BoxCenterContext)

Issue

There is a possibility of the user being able to dismiss the box before box presentation has been completed, ie. before the KVO is added.

When that happens, the app crashes trying to remove a KVO that does not exist.

Question

Is there a way to check for existence of KVO (before trying to remove)?

like image 858
Gizmodo Avatar asked Sep 11 '18 12:09

Gizmodo


2 Answers

observationInfo property is set when there is an observer added

if self.boxView!.observationInfo != nil {

   self.boxView!.removeObserver(self, forKeyPath: "center", context: &BoxCenterContext) 
}
like image 63
Sh_Khan Avatar answered Oct 19 '22 17:10

Sh_Khan


Apple does not provide any API for check existence of observer but you can manage a Bool flag for this. Like when u register KVO you set isObserver bool to true and then before removing observer you need to check isObserver true of false if isObserver is true so remove observer and if it's false don't do any thing.

like image 6
Rakesh Mandloi Avatar answered Oct 19 '22 16:10

Rakesh Mandloi