问题
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?
回答1:
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.
回答2:
There are actually two errors.
Your actual question:
if (firstWord == @"First"){}
needs to be
if ([firstword compare:@"first"]==NSOrderedSame) ...
Only works if firstword isn't nil.
In addition:
NSString *firstWord = [[NSString alloc] init];
firstWord = [textView text];
This looses memory, since you are not "copying" the textview into the string (which wouldn't be possible anyway since it's not mutable), you are simply assigning another string object to the pointer. So the empty string that you've allocated is lost.
Just do
NSString *firstWord;
firstWord = [textView text];
EDIT: making sure the strings have the same pointers would be even more costly, since you would have to keep a table of string objects and lookup every string there so you can either replace your pointer with the "unique" one or add the new string to the table...
来源:https://stackoverflow.com/questions/11389952/issue-comparing-nsstring-literal-and-constant