swiftxcode6addobserver

Why might this [Swift] NSObject.addObserver registration not be calling func observeValueForKeyPath() as expected?


Problematic code follows. [I hope that] the problem is wholly outlined in the question above. Thanks in advance. MJB.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    var some_string:NSString = "one"

    func application ( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]? ) -> Bool
    {
        println("init...")
        self.addObserver( self, forKeyPath: "some_string", options: nil, context: nil )
        self.some_string = "two"
        return true
    }

    override func observeValueForKeyPath ( keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void> )
    {
        println("observeValueForKeyPath...")
    }
}

Solution

  • According to the Apple Documentation, you need to use the dynamic keyword to enable KVO for that property:

    dynamic var some_string : NSString = "one"
    

    Also, the class must inherit from NSObject to make this work, though in your case that is a given with UIResponder.