PDA

View Full Version : getting access through #defined values through strings?




dantastic
Mar 1, 2011, 11:02 AM
Um, I may have painted myself into a corner here.

I have a bunch of #define kMyValue @"Some Arbitrary String"
I use these as it makes it handy to use @"kMyValue" as keys for storing a bunch of stuff in the core data db.

So at one stage I end up with a dictionary with strings & keys. the keys are each named after my #define - example

#define kName @"Enter full name here"
...
[myDict setObject:@"Dan Tastic" forKey:@"kName"];
...
nameLabel.text = [myDict valueForKey:@"kName"];
descriptionLabel.text = kName;


Now I want to print out the *friendly* version of the key - grab the name from the #defined value - how do I do that?? how do I make a variable out of my string?? How do I programatically accomplish the above from an array of dictionary keys?



PhoneyDeveloper
Mar 1, 2011, 11:57 AM
The code you show doesn't make sense. It should be this

[myDict setObject:@"Dan Tastic" forKey:kName];

To print it out do this

NSLog(@"The value of kName is \"%@\"", kName);

dantastic
Mar 1, 2011, 12:54 PM
Right, and if I have a string as

NSString *myString = @"kName";


Then I want to do

NSLog(@"The value of kName is %@", kName);


But using the string in 'myString', something like

NSLog(@"The value of kName is %@", [myString value]);

dantastic
Mar 1, 2011, 01:00 PM
I should probably mention what I'm doing before this gets messy.

I have a bunch of dictionaries, I need a handy key that I can use for everything, the dictionary itself and the core data model.

When it comes to showing the user the friendly version of the key I figured it would be a good idea to just #define the friendly strings against the keys - they are in my array already.

The simple way out is to just create another dictionary but I like this approach if it's possible:)

robbieduncan
Mar 1, 2011, 01:02 PM
Right, and if I have a string as

NSString *myString = @"kName";


Then I want to do

NSLog(@"The value of kName is %@", kName);


But using the string in 'myString', something like

NSLog(@"The value of kName is %@", [myString value]);


You basically cannot do what you are trying to do. #defines are replaced by the pre-processor. Basically it does a search and and replaced so every instance of kName will become @"Enter full name here". Then the compiler runs on that search/replaced code.

dantastic
Mar 1, 2011, 01:14 PM
Right. So another dictionary it is so I suppose..

cheers!