问题比较NSString文字和常量 [英] Issue comparing NSString literal and constant
问题描述
我有一个 NSString
, firstWord
,其值为"First".定义如下:
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"){}
在Objective-C中,比较未返回true或YES.我知道它确实具有与字符串相同的值.因此,来自这我是我很确定问题是我正在比较指针,尽管字符串本身确实具有相同的值,但这里的指针并不相同.那么,如何直接比较字符串本身呢?或者也许更有效地,确保两个字符串对象 do 具有相同的指针,所以我不必进行相对昂贵的字符串比较吗?
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?
推荐答案
那么如何直接比较字符串本身呢?
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,
这是不可能的.一个是字符串文字,存储在应用程序二进制文件的DATA部分中;另一个在应用程序的堆上.在某些情况下(使用 initWithString:@文字字符串"
创建字符串),您将获得相同的地址,但您不应依赖该地址.
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.
这篇关于问题比较NSString文字和常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!