views:

335

answers:

5

I currently have a loop which iterates through an NSArray of NSString objects. I would like an NSString variable to be created on each iteration of the loop, using the currently evaluated NSString object's string value (from the NSArray) as the name of the variable. This is probably best explained through example:

for (i = 0; i < [arrayOfStrings count]; i++) {

    // NSString *<name of variable is [arrayOfStrings objectAtIndex:i]> = [[NSString alloc] init];

}

Is there anyway to accomplish this task? I am using iPhone SDK 3.1. Thanks.

+1  A: 

Not exactly but you could use an NSMutableDictionary to add key/value pairs at runtime where the key is the name from the array of strings. See http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html.

DyingCactus
A: 

If the variables do not exist until runtime then what would make use of them?

Kendall Helmstetter Gelner
I think there are several useful cases for this. One immediate case that comes to my mind, is a situation where need to create some class on demand and instantiate based on the required fields and methods. But possibly the person asking here has a different use case
A: 

You might need to take a look at the Objective-C runtime library support. There are a number of functions that let you add variables, methods, or change method implementations at runtime. For example in your case the class_addIvar function may work for you:

Adds a new instance variable to a class.

BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)
+1  A: 

What you're asking for does not make sense. Variable names do not exist at runtime. They are compiled down to offsets, and the name of the variable is lost (if we're talking about method-local variables. The runtime retains the names of instance variables).

I think the real questions are "Why do you need to do this? What are you trying to accomplish?"

Dave DeLong
A: 

Thanks everyone for your response. The use case for this scenario was what the unknown (google) user suggested where I needed to create a class on demand. However, I figured after a while this was rather poor design and restructured the application to no longer need that functionality. Thanks for all your suggestions anyway!

Skoota