Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

steve1717

macrumors newbie
Original poster
Jul 18, 2007
20
0
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?
 

lancestraz

macrumors 6502a
Nov 27, 2005
898
0
RI
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.
Code:
if ([myString isEqualToString:@"frustration"]) {
	NSLog(@"The strings are equal");
}
 

kpua

macrumors 6502
Jul 25, 2006
294
0
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.