Can a variable be called dynamically in Objective C?

Here is an object and has the following attribute:

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

      

If I want to list these attri I can call

NSLog(aObj.attri1);

      

But can I make 1 as a variable so that I can call it from within the loop? Is it possible to do this 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. By the way, what is this function called? Thank you.

+1


source to share


2 answers


If you want to dynamically access the object object, you can do so using Key Value Coding .

If the class is KVC compliant like most NS classes, you can use valueForKey:

or valueForKeyPath:

to access the property with a string:



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

      

+3


source


The function you're looking for is usually called "variable variables." Objective-C does not have this feature. In fact, most languages ​​don't.



The good news is that you don't really need this feature. Four variables, named the same with a number at the end, are basically equivalent to an array, only if the structure is implicit and not explicit. Just make an attri

array and then you can query it for the numbered item.

+1


source







All Articles