在swift中使用KVC遇到的坑
2020-08-15 本文已影响0人
leaflying
- 在Swift4.0之后,类必须要继承自NSObject,同时还需要在属性前面加上@objc
否则会报错
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<test3.Person 0x600000449880> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
- Cannot convert value of type '[String : String]' to expected argument type '[String : AnyObject]'
实例代码:
import UIKit
class Person:NSObject{
@objc var name:String?
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeys(dict)
}
}
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let dict = ["name":"1234"]
let p1 = Person(dict: dict)
print("\(p1.name!)")
}
}
因为我现在在学习swift,这段代码我是参考网上的代码写的,写出来后一直报错,我也不知道怎么办
后来发现是swift的类型变严格了,于是就有下面两种方法
import UIKit
class Person:NSObject{
@objc var name:String?
init(dict:[String:Any]) {
super.init()
setValuesForKeys(dict)
}
}
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let dict = ["name":"1234"]
let p1 = Person(dict: dict)
print("\(p1.name!)")
}
}
import UIKit
class Person:NSObject{
@objc var name:String?
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeys(dict)
}
}
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let dict = ["name":"1234" as AnyObject]
let p1 = Person(dict: dict)
print("\(p1.name!)")
}
}
如果有什么写的不好的地方,希望大家评论区告诉我,毕竟我也才学swift,很多地方都不懂