1

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.

1

2 Answers 2

3

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]]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You could do this, but it smells a lot like an architectural problem if you do. It is exceptionally rare to have classes that have an arbitrary set of ivars that are accessed through the generic accessors. It is both slow and fragile. Far better to have a more formal, declarative, architecture. Or, alternatively, just use an NSMutableDictionary, potentially encapsulating it in your custom class to provide a clear delineation between "set of goo" and "well defined stuff".
I'm not endorsing this method of coding by any means; my goal was simply to answer the question accurately :). I do agree though that this style of coding is not favorable.
Yup; Totally. Point awarded. :) Just... well.. Don't Do That!
1

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.

2 Comments

All of the scripting language do support it though, in one form or another (Even Python!).
@cwallenpoole: The "in one form or another" is rather important here. It's possible in Python, but this is not a Pythonic thing to do. It's also not idiomatic in Ruby. And even if it were something that's commonly done in those languages, I hardly see how it's relevant that a handful of languages very unlike Objective-C support it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.