3
votes

I'm trying to implement KVC/KVO in Swift 4. Much of the documentation I've read up on for KVC/KVO in Objective-C states that the observer needs to be removed when you are done with it. But, after looking at Apple's documentation of the implementation of KVO using Swift 4, they don't explicitly state whether or not the observer needs to be removed in a deinit method. They do not include a deinit method in the example class definition. But, I do not want to make any assumptions since all the Objective-C documentation I've read states that the observer needs to be removed.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID12

I'm just not sure whether or not the observer needs to be removed through a deinit. Any help or point in the direction of a reference would be great, thanks.

2
thank you, that post is very useful!EGMSSE

2 Answers

3
votes

If you are talking about NSKeyValueObservation: No they don't.

From the transcript of the WWDC 2017 Video "What is new in Foundation"

There is no need for a deinit where I throw away or tear down my observation because it's tied to the life cycle of that observation token. And so when the controller goes away, the observation token will go away.

2
votes

The rules around deregistering observers was relaxed in 10.13, from the Foundation Release Notes (emphasis added):

Relaxed Key-Value Observing Unregistration Requirements

Prior to 10.13, KVO would throw an exception if any observers were still registered after an autonotifying object's -dealloc finished running. Additionally, if all observers were removed, but some were removed from another thread during dealloc, the exception would incorrectly still be thrown. This requirement has been relaxed in 10.13, subject to two conditions:

  • The object must be using KVO autonotifying, rather than manually calling -will and -didChangeValueForKey: (i.e. it should not return NO from +automaticallyNotifiesObserversForKey:)
  • The object must not override the (private) accessors for internal KVO state

If all of these are true, any remaining observers after -dealloc returns will be cleaned up by KVO; this is also somewhat more efficient than repeatedly calling -removeObserver methods.

HTH