reza_khalafi
reza_khalafi

Reputation: 6534

What the difference between setValue and myObject.propertyName in iOS Swift 3.1?

I have object like this:

class Human: NSObject {
    var name:String!
    var age:Int!
}

And make instance from object like this:

let instance = Human()  

And set my values like this:

instance.name = "Kirk"
instance.age = 87

And print it like this:

print("name: \(instance.name)") // Kirk
print("age: \(instance.age)") //87

Every things are OK. but now set my values another way like this:

instance.setValue("Kirk", forKey: "name")
instance.setValue(87, forKey: "age")

Get this error for Int dataType:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key age.'

Why this happened?
And How to fix this because i need to using setValue() function.

Upvotes: 1

Views: 2483

Answers (2)

Bilal
Bilal

Reputation: 19156

Int! can't be represented int Objective-C as other mentioned. This should work

class Human: NSObject {
    var name:String!
    var age : Int;

    init(name:String?, age:Int) {
        self.age = age
        self.name = name
    }
}

Upvotes: 2

Sulthan
Sulthan

Reputation: 130092

Key-value coding (KVC) relies on Objective-C functionality and Int! type is technically an optional value type. Optional value types cannot be represented in Objective-C and that's why the call fails.

You can see the compilation error if you add an explicit dynamic attribute:

class Human: NSObject {
    var name:String!   
    dynamic var age: Int!
}

It would work with Int.

Using implicitly unwrapped optionals in this case is a bad idea anyway. You should have the properties as non-optionals and initialize them in an initializer.

Upvotes: 7

Related Questions