swift,  xcode

Debugging xxx was deallocated while key value observers were still registered with it

Debugging errors that are a result of observers being added to an object and not removed from it can be hard.

Debugging xxx was deallocated while key value observers were still registered with it

Debugging errors that are a result of observers being added to an object and not removed from it can be hard because the error “xxx was deallocated while key value observers were still registered with it” does not tell us anything about the observers in question.

An approach we find useful is to override addObserver function and put a breakpoint the to see what observers are being added to the object.

override func addObserver(observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutablePointer<Void>) {
    print(keyPath)
    super.addObserver(observer, forKeyPath: keyPath, options: options, context: context)
}

If the object is a collection view, a table view, or any other object in a storyboard or a xib file, we can always inherit and use our inherited object in the Class field of the identity inspector.

class CustomCollectionView: UICollectionView {
    deinit {
        print("deinit")
    }

    override func addObserver(observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutablePointer<Void>) {
        print(keyPath)
        super.addObserver(observer, forKeyPath: keyPath, options: options, context: context)
    }
}

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox