简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM