Original blog, reproduced please indicate the source
Classes that use KVC and KVO in Swift must inherit from NSObject
KVC
Key-value coding
is a mechanism for indirectly accessing objects
The value of key is the string of the property name, the returned value is any type and needs to be converted to the desired type
KVC is mainly two methods
(1) Set the corresponding property by key
(2) Get the corresponding property by key
Example
Class testforkvc:nsobject{ var hwccsdn = "Hello World"}var instance = TESTFORKVC () var value = Instance.valueforkey ("H Wccsdn ") as Stringinstance.setvalue (" Hello HwC ", Forkey:" Hwccsdn ")
KVO
Key-value Observing
A mechanism built on the KVC
The main function is to detect changes in object properties
This is a perfect mechanism that does not require the user to design complex observer patterns for themselves
Add the dynamic keyword to the property you want to observe
Example
The first step is to add the dynamic keyword to the properties of the object to be observed
Class toobserver:nsobject{ dynamic var hwcdate = NSDate () func updatedate () { hwcdate = NSDate () }}
The second step is to declare a global variable that distinguishes which property is being observed.
private var mycontext = 0
The third step, addobserver in the class to be observed, removeobserver in the destructor, overrides Observervalueforkeypath
Class testforcsdn:uiviewcontroller{ var testvariable = Toobserver () override func Viewdidload () { Super.viewdidload () testvariable.addobserver (self,forkeypath: "Hwcdate", Options:. New,context:&mycontext)} deinit{ testvariable.removeobserver (self,forkeypath: "HwcDate") } Overfide func Observevalueforkeypath (keypath:string,ofobject:anyobject,change:[nsobject:anyobject],context: unsafemutablepointer<void>) { if (context = = &mycontext) { println ("Changed to:\ (change[ nskeyvaluechangenewkey]!)}} }
In this way, changes can be detected in the function Observevalueforkeypath.
Use of KVC and KVO in Swift