View Full Version : Retrieving an NSString from an NSDictionary

Jun 20, 2008, 10:25 PM
I'm experiencing strange behavior trying to retrieve an NSString from an NSDictionary that has been saved to disk in the form of an NSData object. I can clearly save an NSString in, for example, @"key1" of the NSDictionary. I can even read that object back into an NSString and verify its accuracy using NSLog. The trouble is that I cannot seem to compare that NSString to another NSString. For example:

NSString *myOriginalString = @"frustration";

...place that as the first key in a dictionary. save the dictionary to disk, and then retrieve that dictionary later as myDictionary

NSString *myString = [myDictionary valueForKey@"key1"];

NSLog(@"myString = %@", myString); // works just fine, writes the word 'frustration' to the console

// the problem is this:

if (myString == @"frustration") {
// this doesn't work! It doesn't recognize that myString contains the word 'frustration'

Any ideas?

Jun 20, 2008, 11:01 PM
I don't think it works that way. I'm still new to this but I think you are comparing the string "frustration" to the object myString. So the result would be false. what you want to do is use NSString's "isEqualToString:" method.
if ([myString isEqualToString:@"frustration"]) {
NSLog(@"The strings are equal");

Jun 20, 2008, 11:36 PM
lancestraz has the right solution. == is pointer equality.

It works before writing the dictionary to disk, because you put the NSConstantString instance for @"frustration" in the dictionary and then check the pointers (and NSDictionary doesn't do any copying, so the pointer value is the same).

However, Cocoa can't figure out that the string it reads from disk is the same as the NSConstantString instance, so it creates a brand new NSString, which has a different pointer value.

Use -isEqualToString: to compare NSStrings.

Jun 21, 2008, 06:59 PM
Great -- thanks!