是否可以在目标C中动态调用变量? [英] Is this possible to call variable dynamically in Objective C?

查看:67
本文介绍了是否可以在目标C中动态调用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是对象,并具有以下属性:

Here is the object, and have following attribute:

NSString attri1;
NSString attri2;
NSString attri3;
NSString attri4;

如果我想列出这些属性,可以致电

If I want to list these attri, I can call

NSLog(aObj.attri1);

但是我可以将1作为变量从循环中调用吗?在Objective-C中可以这样做吗?

But can I make the 1 as a variable to call it from a loop? Is this possible to do so in objective-c?

for(int i = 0; i < [array count]; i++)
{
    NSLog(aObj.attri1); //is this possible to become one line, dynamic generated variable
}

谢谢.顺便说一句,这个功能叫什么?谢谢.

Thank you. btw, What is this feature called? Thanks.

推荐答案

如果要动态访问对象的属性,可以使用

If you want to dynamically access a property of an object, that can be done with Key Value Coding.

如果该类与大多数NS类一样都是KVC兼容的,则可以使用valueForKey:valueForKeyPath:来访问带有字符串的属性:

If the class is KVC-compliant, as most NS classes are, you can use valueForKey: or valueForKeyPath: to access a property with a string:

for(int i = 0; i < [array count]; i++) {
    NSLog([[aObj valueForKey:[NSString stringWithFormat:@"attrib%d", i]]);
}

这篇关于是否可以在目标C中动态调用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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