views:

27

answers:

2

I have a nsmutabledictionnary, and when I use setObject:forKey: with a nsstring key it works when I try objectForKey, but if I put a nsmutablestring in the key argument of the SetObject:forKey: method, it's not work when I call objectForKey, it return the last object in the dictionnary...

sorry for my english I do my best... Alex

A: 

If a normal string works, but the mutable one doesn't, then why don't you just add another line of code and convert it to a normal string?

NSString *keyValue = mutableStringVariable;

Thomas Clayson
if you do this, your string KeyValue just point on the mutableStringVariable object, so you have the same object at the end
alex
+2  A: 

Hi Alex,

You should know that NSDictionary (and NSMutableDictionary) copies the key before adding it - thus, if you use a NSMutableString as a key, then modify that same string, the key in the database will still have the old value. This is done for a reason - the key in a NSDictionary should always be static, since it's actually the hash of it that's used for retrieving the associated value.

eliego
So what I can do, I try NSString *myString =[[NSString alloc] initWithString: [@"fr_" stringByAppendingString: myMutableString]];and put myString in the key argument but this not work...
alex
ok it's works! thanx for the great explication in your answer!
alex
The corresponding CFDictionary functions do not copy keys. I use this so I don't need to wrap (e.g.) NSURLConnections to use them as keys. Only do this on objects which don't override `-(NSUInteger)hash`.
tc.
Shit will still hit the fan if you change the object after you've added it as key ;)
eliego