Objective-C从字符串中获取类属性

时间:2022-09-06 21:08:48

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'.

我的应用程序有一个名为“Record”的核心数据模型,它有一些列/属性,比如“日期,column1和column2”。为了保持编程的整洁,以便使我的应用程序适应多种场景,输入字段被映射到plist中的一个核心数据属性(例如,我有一个名为“dataToGet”的字符串变量,值为“column1”。

How can I retrieve the property "column1" from the Record class by using the dataToGet variable?

如何使用dataToGet变量从Record类检索属性“column1”?

1 个解决方案

#1


80  

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:

键值编码机制允许您使用属性名的字符串表示与类的属性进行交互。例如,如果您的记录类有一个名为column1的属性,您可以访问该属性如下:

NSString* dataToGet = @"column1";
id value = [myRecord valueForKey:dataToGet];

You can adapt that principle to your specific needs.

你可以根据自己的具体需要调整这一原则。

#1


80  

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:

键值编码机制允许您使用属性名的字符串表示与类的属性进行交互。例如,如果您的记录类有一个名为column1的属性,您可以访问该属性如下:

NSString* dataToGet = @"column1";
id value = [myRecord valueForKey:dataToGet];

You can adapt that principle to your specific needs.

你可以根据自己的具体需要调整这一原则。