views:

405

answers:

3

I want to use my dictionary keys for output in a grouped table. This has to be localized with all my other content. Can I use an NSLocalizedString as the key?

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    first_array, NSLocalizedString(@"First Array", @"The First Array"),
    second_array, NSLocalizedString(@"Second Array", @"The Second Array"), nil];
+8  A: 

You can, since it is just a string. That said, don't use this technique for dictionaries that you're going to write out and later read back in, because the user may change his or her language in between, and then you'll be looking for the wrong keys.

Peter Hosey
+1  A: 

This looks like a static dictionary which is going to be created once in your program and then not changed again. As such I don't see a problem with it. I take it that as you are creating non-mutable dictionary, this won't be changed and archived; because if it is, then the archive file will not be able to be exchanged between users with different locales, because the keys will be different.

If, however, instead of creating localised arrays and loading them into a dictionary, you could just have a localised plist file which is loaded into the dictionary. It might make your code more readable.

Abizern
+4  A: 

As Peter pointed out, the dictionary only cares that the key is an object that implements the NSCopying protocol. A string statisfies that, and it's contents don't matter as far as legality is concerned.

Perhaps it won't be a problem in this case, but there are many times were one word in one langue will map to two different words in a different language depending on the context of the usage of the word. The reverse is also possible, two words in one language might map to the same word in a different language. This is an unlikely problem to run into, but it's probably best to treat localized values only as values you show to the user, and use some other more tightly defined value to be a key.

Jon Hess