I never used Swift4 before, and dont know how to use KVC in it.
I try to create model with Dictionary, here the code:
class Person : NSObject {
var name: String = ""
var age: Int = 0
init(dict: [String : Any]) {
super.init()
self.setValuesForKeys(dict)
}
}
let dict: [String : Any] = ["name" : "Leon", "age" : 18]
let p = Person(dict: dict)
print(p.name, p.age)
There I get two question:
1. Why dont I using AnyObject? "Leon"and18 was infer to String and Int, does it using in KVC?
2. @objc var name: String = "" , this form is worked, but I can not understand it.
Thanks for all helps.
To implement KVC support for a property in Swift 4, you need two things:
Since the current implementation of KVC is written in Objective-C, you need the
@objcannotation on your property so that Objective-C can see it. This also means that the property's type needs to be compatible with Objective-C.In addition to exposing the property to Objective-C, you will need to set up your notifications in order for observers to be notified when the property changes. There are three ways to do this:
For stored properties, the easiest thing to do is to add the
dynamickeyword like so:This will allow Cocoa to use Objective-C magic to automagically generate the needed notifications for you, and is usually what you want. However, if you need finer control, you can also write the notification code manually:
The
automaticallyNotifiesObserversOf<property name>property is there to signify to the KVC/KVO system that we are handling the notifications ourselves and that Cocoa shouldn't try to generate them for us.Finally, if your property is not stored, but rather depends on some other property or properties, you need to implement a
keyPathsForValuesAffecting<your property name here>method like so:In the example above, an observer of the
bazproperty will be notified when the value forfooor the value forbarchanges.