KVO working once in Swift

2020-07-10 10:25发布

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

Here's a GIST of my code

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

Any idea ?

EDIT: It seems like I found a temporary solution using:

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

1条回答
Explosion°爆炸
2楼-- · 2020-07-10 11:00

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

dynamic var lifes = 0

查看更多
登录 后发表回答