DNB5brims
DNB5brims

Reputation: 30578

Is this possible to call variable dynamically in Objective 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);

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.

Upvotes: 1

Views: 769

Answers (2)

chown
chown

Reputation: 52738

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

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]]);
}

Upvotes: 3

Chuck
Chuck

Reputation: 237040

The feature you're looking for is generally called "variable variables." Objective-C does not have this feature. Actually, most languages don't.

The good news is that you don't actually need this feature. Four variables named the same thing with a number at the end is basically equivalent to an array, only with the structure being implicit rather than explicit. Just make attri an array and then you can ask it for a numbered item.

Upvotes: 1

Related Questions