Search code examples
objective-cnsstringnsstringencoding

NSOrderedSame not YES even though values in NSLog are equal


I have a simple but strange problem. I compare to strings, (taken from different xmls), to find out if they match. If i trace the variables via NSLog, they LOOK the same, but obviously are not. So i guess it's got to do something with its encodings, but i don't know what. Anyone help?

I found out that the strings are not of the same length, but i can't find whitespaces:

Code:

NSString* value1 = [mymovieId stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString* value2 = [movieId stringByReplacingOccurrencesOfString:@" " withString:@""];

NSLog(@"%@ == %@", mymovieId, movieId);
NSLog(@"%i / %i", value1.length, value2.length);

if ([value1 compare:value2] == NSOrderedSame) {
    NSLog(@"YES!");
} else {
    NSLog(@"NO!");
}

result:

2012-01-17 20:40:06.044 Appname[6307:f803] 75175343 == 75175343
2012-01-17 20:40:06.044 Appname[6307:f803] 9 / 8
2012-01-17 20:40:06.045 Appname[6307:f803] NO!

Certainly this problem onyl exists due to my rawdata, but I can't upload my whole project here, so i hope someone knows an answer anyway.

Thanx Wolfgang


Solution

  • Try logging the strings as data:

    NSLog(@"mymovieId: %@", [mymovieId dataUsingEncoding:NSUnicodeStringEncoding]);
    NSLog(@"movieId: %@", [movieId dataUsingEncoding:NSUnicodeStringEncoding]);
    

    That will print hex dumps of the strings, making it possible to see unprintable characters.

    From your comment it looks like one of your strings starts with a newline. Try this:

    movieId = [movieId stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    mymovieId = [mymovieId stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];