Accessing all class property values dynamically

70 Views Asked by At

So basically what I'm trying to do is list all properties of an object in a tableview in a key = value format.

But I want this to be independent of future changes to the object, so that if a new property is added later, no changes will be needed to my code.

So far I can access the properties via Mirror, but I run into problems when I'm trying to access the properties via value(forKey:), even though the class is inheriting NSObject it crashes with:

this class is not key value coding-compliant for the key

Some properties work while others don't, which I'm guessing is down to some of them being private and others @objc variables?

So is there any way to pre-validate that a key (property) can be accessed via value(forKey:) - so it doesn't end in a crash, so I if nothing else can show the values of the accessable properties?

Better yet, is there another way of accessing all properties and values of a given object in a dynamic way? (handling later additions of properties)

Code snippet:

let properties = Mirror(reflecting: currentUser).children.compactMap { $0.label }
if properties.count > 0 {
    for property in properties {
        if let test = currentUser[property] {
            newData.append( (name: property, value: currentUser.value( forKey: property ).debugDescription) )
        }
    }
}
1

There are 1 best solutions below

0
On

What you might be able to do is make your object conform to Encodable. That way, you could simply convert it into JSON (or some other format), then make your table view dynamically pull out all the keys and values from the JSON.

As long as any future changes to the object don’t break Encodable compliance, the table view will still be able to parse whatever JSON it receives.