更改 Swift class 中的绑定变量

Change bound variable in Swift class

我有一个标签,它绑定到实例中的一个变量。 当我更改变量时,我可以打印出新内容,但标签保留原始内容。

class myClass: NSObject {

    var text : String = "Initial"

    override init() {

        text = "Init"
    }

    func change() {
        text = "Changed"
    }
}


@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var instance = myClass()

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        instance.change()
        print(instance.text)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

print(instance.text) 给我 "Changed" 但标签保留 "Init".

为什么绑定在这种情况下不起作用?

标签有 "Bind to App Controller" "self.instance.text" 绑定

谢谢

When Swift APIs are imported by the Objective-C runtime, there are no guarantees of dynamic dispatch for properties, methods, subscripts, or initializers. The Swift compiler may still devirtualize or inline member access to optimize the performance of your code, bypassing the Objective-C runtime.

You can use the dynamic modifier to require that access to members be dynamically dispatched through the Objective-C runtime. Requiring dynamic dispatch is rarely necessary. However, it is necessary when using using APIs like key–value observing.

绑定使用键值观察。将 text 属性 更改为 dynamic var text : String,将 var instance 更改为 dynamic var instance