问题
Is it possible to dynamically name a variable (mine is specifically a char array) by the name of a key that is read from NSDicttionary .plist?
NSMutableDictionary *readDict = [[NSMutableDictionary alloc] initWithContentsOfFile:@"path/to/plist"];
NSDictionary * getKeys = [readDict objectForKey:@"info"];
for (id key in getKeys) {
NSLog(@"%@ %@", key, [getKeys objectForKey:key]);
// output key1 some data in here== (repeats with key2, etc.)
NSData *theData = [getKeys objectForKey:key];
const char *hexData = theData.bytes;
|
|__ so for each iteration in the loop it would be:
i.e. key1, key2... to match the plist key names
} instead of a static variable name.
plist:
<dict>
<key>info</key>
<dict>
<key>key1</key>
<data>
some data in here==
</data>
<key>key2</key>
<data>
some data in here==
</data>
</dict>
</dict>
回答1:
Short answer: No
Explanation:
You are declaring a local variable whose scope is just the loop it is declared in. Such variables have static compile-time names assigned.
Furthermore there is no point in changing the name dynamically, the name of a variable does not effect its contents or change its lifetime or scope - even if you could change the name the variable would still only exist for a single iteration of the loop, at the end of an iteration the variable is destroyed, at the start of the next iteration a new variable is created.
Just in case:
Sometimes people ask if they can create a long-lived variable with a dynamic name, so they can find it by name later. While you still cannot do that (as variables have compile-time names) the standard suggestion for this case is to use an NSMutableDictionary - dictionaries are a runtime mapping from a key, typically a string, to any object type (which indirectly includes any value type; such as, say, a char *; as they can be wrapped as objects). If this is your goal - to create a collection of "named" character pointers - then this is the route to take. However you will need to ensure yourself that whatever these character pointers refer to also stays around, which in your case requires you to keep the NSData objects around these pointers refer to (you can keep these obkjects in the same dictionary, e.g. create a class with NSData * and char * properties and store instance of this in your dictionary.
来源:https://stackoverflow.com/questions/21508537/nsdictionary-objectforkey-to-var-name