GED125
GED125

Reputation: 496

Swift: Unable To Set Description on Subclass of NSObject

I have built a custom class that looks something like this:

import UIKit

class Device: NSObject {

    var id = String()
    var name = String()
    var type = String()
    //var description = String()  //Cannot override with a stored property 'description'

}

Very simple class, and I am inheriting NSObject so I can use "setValue(value, forKey: keyName)". However, when I do the following:

device.setValue("My Description", forKey: "description")

I am getting the following error:

'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'

So insummary, I can't override the NSObject.description, but when I try to set it I am getting an error. Anyone run into this before?

Upvotes: 1

Views: 773

Answers (2)

Pranavan SP
Pranavan SP

Reputation: 1865

You can only get the description property, you can't set it.

In Objective-C string classes, the class description for NSMutableString specifies that the class inherits from NSString. description, when you try to set description it will be getting an error.

Method 1

While using setValue(value, forKey: keyName) Use can store property value by using.

class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override var description: String {
        get {
            return self.description
        }
        set(newvalue) {
            descriptions = newvalue
        }
    }
}

Using above code, method setValue for key description value store into the descriptions. while you get the value you can use descriptions. Also, it does not affect on description get.

Method 2

Overriding setValue function. like below.

class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override func setValue(_ value: Any?, forKey key: String) {
        if key == "description"{
           if let desc = value as? String{
               self.descriptions = String()
               self.descriptions = desc
            }
        }else{
            super.setValue(value, forKey: key)
        }
    }
}

Upvotes: 1

Kevin
Kevin

Reputation: 17566

Look at where description is defined. It is listed in the NSObjectProtocol as

public var description: String { get }

You can only get the description property, you can't set it.

In Objective-C, description is implemented in most classes as a method; it has no underlined storage. The swift equivalent would be a computed property:

public override var description: String {
    return "I'm an object"
}

tl;dr Use a computed property instead of a stored property

class CustomObject : NSObject {
    private var des: String
    override var description: String {
        get {
            return des
        }
        set(newValue) {
            des = newValue
        }
    }

    init(string: String) {
        des = string
    }
}

Upvotes: 2

Related Questions