KVO在Swift中工作过一次 [英] KVO working once in Swift

查看:57
本文介绍了KVO在Swift中工作过一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中使用KVO,但是方法"observeValueForKeyPath"仅被调用一次.

I'm trying to use KVO in Swift, but the method "observeValueForKeyPath" is called once.

这是我的代码的GIST

我尝试使用NSNumber代替Int,将所有选项添加到addObserver,但是在加载视图时,该方法仍然被调用一次.

I tried to use NSNumber instead of Int, add all options to addObserver, but the method is still call once when my view load.

有什么主意吗?

似乎我使用以下方法找到了一个临时解决方案:

It seems like I found a temporary solution using:

var lifes: Int {
    willSet {
        willChangeValueForKey("lifes")
    }
}

推荐答案

KVO需要动态分配,因此需要将dynamic修饰符添加到属性中:

KVO requires dynamic dispatch, so the dynamic modifier needs to be added to the property:

dynamic var lifes = 0

这篇关于KVO在Swift中工作过一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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