Swift optional property using KVC causes crash -
i found using kvc in swift causes many problems, optional properties.
here specific problem:
here class named person. has normal property called age,and optional(int) property called ageoptional.
class person: nsobject { var age: int var ageoptional: int? override init(age: int){ self.age = 0 } }
now, use kvc in person's instance:
//new instance var person = person() //kvc normal property: work person.setvalue(28, forkeypath: "age") //but, time ,it doesn't work well!!!! person.setvalue(28, forkeypath: "ageoptional")
the app crashes, , here exception:
2015-07-11 11:17:31.546 cfruntime[4646:607] *** terminating app due uncaught exception 'nsunknownkeyexception', reason: '[ setvalue:forundefinedkey:]: class not key value coding-compliant key ageoptional.'
i found that, if property optional, kvc couldn't find key. but,i can't find useful key optional property ,and resolve situation.
you have solved problem perfectly. cannot use kvc on optional int property, because kvc cocoa / objective-c, , objective-c cannot see optional int - not bridged objective-c. objective-c can see types bridged objective-c:
class types derived nsobject
class types exposed
@objc
swift structs bridged
objective-c can see optional wrapping of types - almost. can see optional wrapping bridged struct, if struct directly bridged. int not directly bridged; bridged nsnumber, not directly (it has wrapped). thus, objective-c cannot see swift member typed int?
.
if need optional, , if need use kvc on it, declare nsnumber?
, not int?
. personally, doubt whether either of things true; since converting apps objective-c swift, i've found don't need kvc internally, , kvc-based solutions can done other, better way.
Comments
Post a Comment