Objective-C 从字符串中获取类属性 [英] Objective-C get a class property from string

查看:27
本文介绍了Objective-C 从字符串中获取类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过许多针对其他语言的类似问题,但我正在寻找特定场景.

I've heard a number of similar questions for other languages, but I'm looking for a specific scenario.

我的应用程序有一个名为记录"的核心数据模型,它有许多列/属性,如日期、列 1 和列 2".为了保持编程干净以便我可以使我的应用程序适应多种场景,输入字段被映射到 plist 中的核心数据属性(例如,我有一个名为dataToGet"的字符串变量,值为column1".

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

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

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

推荐答案

键值编码 机制允许您使用属性名称的字符串表示与类的属性进行交互.因此,例如,如果您的 Record 类有一个名为 column1 的属性,您可以按如下方式访问该属性:

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.

这篇关于Objective-C 从字符串中获取类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆