Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a Key in NSMutableDictionary?

I am having a NSMutableDictionary. I have to dynamically rename any Key in the dictionary to a new value, in my code.. I can't find any built-in API to do this..

How can I do this? Is there any built-in API available to do this?

Thanks everyone..

like image 405
EmptyStack Avatar asked Feb 02 '11 07:02

EmptyStack


1 Answers

// assumes that olkdey and newkey won't be the same; they can't as
// constants... but...
[dict setObject: [dict objectForKey: @"oldkey"] forKey: @"newkey"];
[dict removeObjectForKey: @"oldkey"];

Think about what "directly editing an existing key" means. A dictionary is a hash; it hashes the contents of the keys to find a value.

What happens if you were to change the contents of a key? The key would need to be rehashed (and the dictionary's internal structures re-balanced) or the value would no longer be retrievable.

Why do you want to edit the contents of a key in the first place? I.e. what problem does that solve that the above does not?

like image 122
bbum Avatar answered Sep 19 '22 17:09

bbum