为什么这个 [Swift] NSObject.addObserver 注册没有按预期调用 func observeValueForKeyPath()?
Why might this [Swift] NSObject.addObserver registration not be calling func observeValueForKeyPath() as expected?
下面是有问题的代码。 [我希望]问题在上面的问题中得到了完整的概述。提前致谢。 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...")
}
}
根据 Apple Documentation,您需要使用 dynamic
关键字为 属性 启用 KVO:
dynamic var some_string : NSString = "one"
此外,class 必须继承自 NSObject
才能使这项工作正常进行,但在您的情况下,UIResponder
.
是给定的
下面是有问题的代码。 [我希望]问题在上面的问题中得到了完整的概述。提前致谢。 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...")
}
}
根据 Apple Documentation,您需要使用 dynamic
关键字为 属性 启用 KVO:
dynamic var some_string : NSString = "one"
此外,class 必须继承自 NSObject
才能使这项工作正常进行,但在您的情况下,UIResponder
.