John Doe
John Doe

Reputation: 2491

Comparing strings is giving false in Objective-C

I am comparing two strings using isEqual method and it is giving NO.

if ([trie.name isEqual:string]) {
    isFound = YES;
    break;
}

The trie.name is a string initialized using [[NSString alloc] initWithCharacters:&uchar length:ucharLen], where uchar is a unichar. The string is a constant string @"N". I have checked the hash values and both differ. I am not sure why creating a string using different initializer gives different hash for the same string value. In this case, how to check for string equality?

Please see the attached screenshot of the debug variables.

string equal error


Currently, I am using the code:

NSString *string = @"Pirates";
unichar uchar = [string characterAtIndex:0];
size_t ucharLen = sizeof(uchar);
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:ucharLen];
XCTAssertTrue([str isEqual:@"P"]);

If I given the length: as 1, it works properly. How to get the length of the unichar. Will it always be 1 so that I can hardcode 1 in this case?

Upvotes: 0

Views: 60

Answers (1)

rmaddy
rmaddy

Reputation: 318804

The problem is with:

unichar uchar = [string characterAtIndex:0];
size_t ucharLen = sizeof(uchar);
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:ucharLen];

You are creating a string from a single unichar which means the length needs to be 1. But the sizeof(unichar) returns 2 since unichar is a 16-bit (2-byte) value so you end up telling the string you are passing 2 characters, not 1.

So the resulting string contains two characters - the one you actually want and a second, random bit of garbage that happens to be at that memory address.

Just hardcode 1:

unichar uchar = [string characterAtIndex:0];
NSString *str = [[NSString alloc] initWithCharacters:&uchar length:1];

Upvotes: 2

Related Questions