iosswiftiphonecrashkey-value-coding

setValue:forKey is always crashing in swift


I have below use case:

class Foo: NSObject {
    var bar = ""
}

let foo = Foo()
foo.setValue("A name", forKey: "bar") //throws exception: this class is not key value coding-compliant for the key bar.
print("Foo.bar: \(foo.bar)")

Apple documentation (here) sais that in Swift each class subclasing NSObject becomes by default key value compliant. If so why am I getting not key value compliant exception?

Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default.

Am I missing something? Dose any one know which could be the problem?

Note: I tried to make the "bar" property NSString but i got the same exception.


Solution

  • To implement KVC(Key-Value Coding) support for a property. you need the @objc annotation on your property, Since the current implementation of KVC is written in Objective-C, After adding @objc, Objective-c can see it.

    class Foo: NSObject {
        @objc var bar = ""
    }
    let foo = Foo()
    foo.setValue("A name", forKey: "bar")
    print("Foo.bar: \(foo.bar)")