idris yıldız
idris yıldız

Reputation: 2117

NSKeyValueObservingOptions error on swift

sometime when I call ignoreFrameChanges method I get this error:

Cannot remove an observer, for the key path "frame" from <......> because it is not registered as an observer.

How can I control before remove that observe, if there is any observe with frame name or not?

func watchFrameChanges() {

    addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, context: nil)
}   

func ignoreFrameChanges() {

    removeObserver(self, forKeyPath: "frame")    
}

Upvotes: 0

Views: 1755

Answers (1)

Sandeep
Sandeep

Reputation: 21144

It seems like you call ignoreFrameChanges method even when the class is not observing for 'frame'.

Would it be possible to use init and deinit to observe and remove observer ? That would make sure that you always observe and remove the observer when it gets released.

You could also use some variable to track the observation like some boolean value as such,

var isObserving = false

func watchFrameChanges() {
    isObserving = true
    addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, context: nil)
}   

func ignoreFrameChanges() {
    if !isObserving { return }
    removeObserver(self, forKeyPath: "frame")    
}

Upvotes: 2

Related Questions