Before SWIFT4, using KVO only needs to inherit nsobject. However, after the SWIFT4 has changed, you must add the @objcmembers modifier before class, otherwise there will be no effect.
Here's an example: if you define a person class that wants to listen to its KVO changes in addition to inheriting nsobject, you must also add the @objcmembers modifier before class, otherwise it will not work.
@objcMembers class Person:nsobject {
var name:string?
var age:int=0
Override Init () {
Super.init ()
}
Init (Dic:[string:any]) {
Super.init ()
Self.setvaluesforkeys (DIC)
}
Override Func SetValue (_ Value:any?, Forundefinedkey key:string) {
}
}
This is used to validate the JSON-to-model for convenience.
Class Viewcontroller:uiviewcontroller {
Override Func Viewdidload () {
Super.viewdidload ()
Let JSON = [' name ': ' Zhang San ', ' age ': ' 20 ']
Let p = person (Dic:json)
Print ("----->>", p.name)
}
Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
Dispose of any resources the can be recreated.
}
}
The result is output:----->>Optional (" Zhang San "), if you remove @objcmembers this modifier will not work, the result is output:----- >> Nil.
So in the SWIFT4 to use KVO must add @objcmembers otherwise it will not work.
If the project uses this kind of KVO to do the JSON to the model, you need to make the appropriate adjustments, because for today encountered this problem, resolved after the record, so that you or others to learn the reference.
Jane Book Address: Code Life
Use of iOS swift4 KVO