swiftkey-value-observingnsobjectthrowaddobserver

Swift: which class owns the .New property used in NSObject.addObserver( ... options: .New )?


The current best practice for KVO in Swift is well documented in this SO post, and would look something like this:

someObject.addObserver( self, forKeyPath: "someProperty", options: .New, 
    context: &self.someContext )

I want to simplify memory management problems by encapsulating this in an ObserversManager (say) class, so I can do things like this:

func observe ( observed: NSObject, observer: NSObject, keyPath: String, 
    context: Int )
{
    observed.addObserver( observer, forKeyPath: keyPath, options: .New, 
        context: context ) { ... }
}

func removeObserversByObserver ( observer: NSObject ) { ... }
func removeAllObservers () { ... }

The problem is that the above func observer throws the following compile time error, which i am at present powerless to fix, as the official documentation does not detail the answer afaict. Could not find member 'New'


Solution

  • The error message is misleading. The problem is that the context: parameter is a pointer, not an Int:

    func observe ( observed: NSObject, observer: NSObject, keyPath: String,
        context: UnsafeMutablePointer<Void> )
    {
        observed.addObserver(observer, forKeyPath: keyPath, options: .New,
                             context: context)
    }