Create variable during run-time in Objective-C
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)开发者_如何学C 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.
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.
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)
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?"
If the variables do not exist until runtime then what would make use of them?
精彩评论