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")
}
}
KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.
KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.
Key-Value Observing, KVO for short, is an important concept of the Cocoa API. It allows objects to be notified when the state of another object changes.
The next option is to use key-value observing from Foundation, which has new and improved Swift APIs that utilize Key-Path expressions. This works well with a centralized AppSettings class. However, it requires inheriting from NSObject and making the properties that you wish to observe @objc and dynamic .
The concept KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.
Using the dynamic keyword to achieve KVO with NSObject subclasses is described in the Key-Value Observing section of the Adopting Cocoa Design Conventions chapter of the Using Swift with Cocoa and Objective-C guide: Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects.
Include KVO/KVC functionality as part of core Swift: The current KVO/KVC are defined as part of Foundation. They don’t need to be moved, but Swift needs an equivalent that can bridge, and is cross platform.
Currently Swift does not support any built in mechanism for observing property changes of objects other than 'self', so no, it does not support KVO. However, KVO is such a fundamental part of Objective-C and Cocoa that it seems quite likely that it will be added in the future.
KVO requires dynamic dispatch, so the dynamic
modifier needs to be added to the property:
dynamic var lifes = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With