在Swift类中更改绑定变量 [英] Change bound variable in Swift class

查看:76
本文介绍了在Swift类中更改绑定变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签,该标签具有与实例内部变量的绑定。
更改变量后,我可以打印出新内容,但标签保留原始内容。

I have a label with a binding to a variable inside an instance. When I change the variable, I can print out the new content but the label keeps the original content.

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)给我已更改,但标签保留初始化。

print(instance.text) gives me "Changed" but the label keeps "Init".

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

Why does the binding not work in this case?

标签具有绑定到App Controller self.instance.text绑定

The label has a "Bind to App Controller" "self.instance.text" binding

谢谢

推荐答案


API是由Objective-C运行时导入的,不能保证动态分配属性,方法,下标或初始化程序。 Swift编译器仍然可以绕过Objective-C运行时,取消虚拟化或内联成员访问以优化代码的性能。

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.

您可以使用dynamic修饰符来要求动态地访问成员通过Objective-C运行时调度。几乎不需要动态调度。但是,在使用诸如键值观察之类的API时很有必要。

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实例转换为动态var实例

Bindings use key–value observing. Change the text property to dynamic var text : String and var instance to dynamic var instance.

这篇关于在Swift类中更改绑定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆