Objective-C get a class property from string
I've heard a number of similar questions for other languages, but I'm looking for a specific scenario.
My app has a Core Data model called "Record", which has a number of columns/properties like "date, column1 and column2". To keep the programming clean so I can adapt my app to multiple scenarios, input fields are mapped to a Core Data property inside a plist (so for example, I have a string variable called "dataToGet" with a value of 'column1'.
How can I retrieve the property "column1" from the Record class by using the dataToGet variable?
Solution 1:
The Key Value Coding mechanism allows you to interact with a class's properties using string representations of the property names. So, for example, if your Record
class has a property called column1
, you can access that property as follows:
NSString* dataToGet = @"column1";
id value = [myRecord valueForKey:dataToGet];
You can adapt that principle to your specific needs.