Retrieving an NSString from an NSDictionary

Discussion in 'Mac Programming' started by steve1717, Jun 20, 2008.

  1. macrumors newbie

    Jul 18, 2007
    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"; 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?
  2. macrumors 6502a


    Nov 27, 2005
    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");
  3. macrumors 6502

    Jul 25, 2006
    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.
  4. thread starter macrumors newbie

    Jul 18, 2007

Share This Page