Iphone NSSet中的NSString查找

Iphone NSSet中的NSString查找,iphone,objective-c,Iphone,Objective C,如何在NSSet中找到某个字符串(值)? 这必须使用谓词来完成吗?如果是,怎么做 NSMutableSet *set = [[NSMutableSet alloc] init]; [set addObject:[[[NSString alloc] initWithFormat:@"String %d", 1] autorelease]]; [set addObject:[[[NSString alloc] initWithFormat:@"String %d", 2] autorelease]]

如何在NSSet中找到某个字符串(值)?
这必须使用谓词来完成吗?如果是,怎么做

NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 1] autorelease]];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 2] autorelease]];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 3] autorelease]];
现在我想检查集合中是否存在“字符串2”。
来自:


包含有关使用谓词的更多信息。最后包含可能需要的所有操作的信息。

可能成员:在这里工作

member:
Determines whether the set contains an object equal to a given object, and returns that object if it is present.

- (id)member:(id)object
Parameters
object
The object for which to test for membership of the set.
Return Value
If the set contains an object equal to object (as determined by isEqual:) then that object (typically this will be object), otherwise nil.

Discussion
If you override isEqual:, you must also override the hash method for the member: method to work on a set of objects of your class.

Availability
Available in iOS 2.0 and later.
Declared In
NSSet.h

如果字符串的内容相等,则字符串相等,因此您可以执行以下操作:

NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil];
BOOL containsString2 = [set containsObject:@"String 2"];
在这里使用
NSPredicate
有点过分,因为
NSSet
已经有了
-member:
方法和
-containsObject:
方法

NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil];
BOOL containsString2 = [set containsObject:@"String 2"];
可能有效,也可能无效。编译器可能会也可能不会为同一@“”字符串创建不同的对象,因此我宁愿使用MATHCES谓词:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"String 2"];

严格地说,如果字符串的内容相等,那么字符串就不相等(在ANSI C的意义上)。如果字符串的指针值相等,则字符串相等。但是,您确实不需要谓词,因为
-member:
-containsObject:
方法不比较对象,而是调用-isEqual:method-在nsstring的情况下,该方法将实际比较对象的内容,而不是对象本身。@KPM除了这不是ANSI C,这是Objective-C,其中,
NSString
类重写了
-isEqual:
方法,以便在两个字符串之间进行类似strcmp的比较。严格来说,如果两个字符串的内容相等,那么它们是相等的。(我不是说一致性,这是你从两个指针得到的结果是一样的)下面的答案更符合我的期望,但谢谢你把我介绍给NSPredicate!
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"String 2"];