检查NSString实例是否包含在NSArray中 [英] Check if NSString instance is contained in an NSArray
问题描述
我有一个字符串数组,我想检查一个字符串是否包含在数组中。如果我在数组上使用 containsObject
:message,我得到正确的结果。是否所有 NSString
具有相同字符串的对象指向同一对象?或者为什么 containsObject
:working?
I have an array with a bunch of strings and I want to check if a certain string is contained in the array. If I use the containsObject
: message on the array, I'm getting correct results. Do all NSString
objects with the same string point to the same object? Or why is the containsObject
: working?
NSArray *stringArray = [NSArray arrayWithObjects:@"1",@"2",@"3",anotherStringValue, nil];
if([stringArray containsObject:@"2"]){
//DO SOMETHING
}
推荐答案
是的,硬编码的NSStrings(字符串文字)(任何 @...$ c $
Yes, hard-coded NSStrings (string literals) (that is any @"..."
in your source code) are turned into strings that exist indefinitely while your process is running.
但是 NSArray 的<$ c $ c> containsObject:方法在其对象上调用 isEqual:
,因此甚至是动态创建的字符串,如 [NSString stringWithFormat:@%d,2]
会在示例代码段中返回 YES
。
这是因为NSString的 isEqual:
(或更确切地说,它的 isEqualToString:
)实现对于包含非常相同的字符序列的任何字符串对,在内容感知(与比较指针身份)之间返回 YES
However NSArray's containsObject:
methods calls isEqual:
on its objects, hence even a dynamically created string such as [NSString stringWithFormat:@"%d", 2]
would return YES
in your sample snippet.
This is because NSString's isEqual:
(or more precisely its isEqualToString:
) method is implemented to be content aware (vs. comparing pointer identities) and thus returns YES
for any pair of strings containing the very same sequence of characters (at time of comparison), no matter how and when they were created.
要检查等号(指针)标识,你必须枚举你的数组,并通过
To check for equal (pointer-)identity you'd have to enumerate your array and compare via
NSString *yourString = @"foo";
BOOL identicalStringFound = NO;
for (NSString *someString in stringArray) {
if (someString == yourString) {
identicalStringFound = YES;
break;
}
}
(你很可能不会想要, )。
(which you most likely wouldn't want, though).
或以更方便的方式:
BOOL identicalStringFound = [stringArray indexOfObjectIdenticalTo:someString] != NSNotFound;
(您很可能不会想要这个)。
(you most likely wouldn't want this one either).
总结:
来自 containsObject:
的肯定回复是 NOT ,因为文字字符串共享同一个常量实例 BUT ,因为 containsObject:
通过约定调用 isEqual:
,这是内容感知的。
So the reason you're getting a positive reply from containsObject:
is NOT because literal strings share the same constant instance, BUT because containsObject:
by convention calls isEqual:
, which is content aware.
You might want to read the (short) documentation for isEqual:
from the NSObject protocol.
这篇关于检查NSString实例是否包含在NSArray中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!