且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查NSString实例是否包含在NSArray中

更新时间:2023-11-25 23:44:40

是的,硬编码的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> 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.

您可能想从 isEqual:的(简短)文档/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual%3a\">NSObject protocol

You might want to read the (short) documentation for isEqual: from the NSObject protocol.