如何使用保存其名称的String访问属性/变量 [英] How to access a property/variable using a String holding its name
问题描述
如果我在Objective C中有两个变量,就像这样,其中一个保存另一个的名称为字符串
If I had two variables in Objective C like this where one holds the name of the other as a string
NSInteger result = 4;
NSString * theName = @"result";
我最好如何使用字符串而不是变量的引用访问第一个变量?例如,如果我有很多变量,并生成一个我需要的代码的名称,我需要一个方法来获取到该变量使用该字符串。
How would I best access the first variable using the string instead of a reference to the variable? For instance if I had a lot of variables and would generate the name of the one I need by code I'd need a way to get to the variable using that string.
推荐答案
虽然没有直接回答您的问题,可以通过
Though not directly answering your question, it's possible to access properties (or ivars) of an object by
[object setValue:@"value" forKey:theName]
[object valueForKey:theName]
(感谢kevboh!)
Similarly, the getter is [object valueForKey:theName]
(thanks kevboh!)
这篇关于如何使用保存其名称的String访问属性/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!