I found that using KVC in Swift causes many problems, especially with optional properties.
Here is my specific problem:
Here is a Class named Person. It has a normal property called age,and a Optional(Int) property called ageOptional.
class Person: NSObject {
var age: Int
var ageOptional: Int?
override init(age: Int){
self.age = 0
}
}
Now, I use KVC in Person's instance:
//new a instance
var person = Person()
//kvc for normal property: it work well
person.setValue(28, forKeyPath: "age")
//but, this time ,it doesn't work well!!!!
person.setValue(28, forKeyPath: "ageOptional")
The app crashes, and here is the exception:
2015-07-11 11:17:31.546 CFRuntime[4646:607] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]:
this class is not key value coding-compliant for the key ageOptional.'
I found that, if a property is optional, KVC couldn't find the key. But,I can't find the useful key for an optional property ,and resolve this situation.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…