Search code examples
objective-cstringcocoa-touchnsstringstring-literals

Issue comparing NSString literal and constant


I have an NSString, firstWord, that has the value of "First". It was defined like this:

NSString *firstWord = [[NSString alloc] init];

firstWord = [textView text];

However, when I try to check its value, like so:

if (firstWord == @"First"){}

The comparison does not return true, or YES I guess in Objective-C. I know that it does have the same value as a string. So, from this I am pretty sure that the issue is that I am comparing pointers, which are not the same here, even though the strings themselves do have the same value. So how can I directly compare the strings themselves? Or maybe more efficiently, make sure the two string objects do have the same pointer, so I don't have to the do the relatively costly string comparison?


Solution

  • So how can I directly compare the strings themselves?

    String comparison in Cocoa is done with isEqualToString:.

    Or maybe more efficiently, make sure the two string objects do have the same pointer,

    This isn't possible. One is a string literal, stored in the DATA section of your app's binary; the other is on your app's heap. In certain circumstances (creating a string using initWithString:@"literal string") you'll end up with the same address, but you shouldn't rely on that.

    As an aside, you don't need to -- in fact, shouldn't, because you're creating a leak -- allocate a string before assigning the text view's text to the pointer.