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

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

问题描述

我听说过其他语言的一些类似问题,但我正在寻找一个特定的场景。



我的应用程序有一个核心数据模型称为记录,它有一些列/属性,如date,column1和column2。为了保持编程清洁,我可以使我的应用程序适应多个场景,输入字段映射到一个核心数据属性在plist(例如,我有一个名为dataToGet的值为'column1'的字符串变量。 / p>

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

解决方案

键值编码机制允许你使用属性名称的字符串表示与类的属性交互。例如,如果你的 Record 具有 column1 的属性,您可以按如下方式访问该属性:

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

您可以根据您的特定需求调整这项原则。


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.

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

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