2011-07-03 65 views
10

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

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]]; 

现在我想检查'String 2'是否存在于集合中。

回答

6

Apple's Developer Site

NSSet *sourceSet = [NSSet setWithObjects:@"One", @"Two", @"Three", @"Four", nil]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith 'T'"]; 
NSSet *filteredSet = [sourceSet filteredSetUsingPredicate:predicate]; 
// filteredSet contains (Two, Three) 

This article from Ars Technica包含使用谓词一些更多的信息。最后,Apple's BNF guide for predicates包含有关可能需要的所有操作的信息。

+0

下面的答案更是我希望的,不过还是谢谢你把我介绍给NSPredicate! –

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 
43

字符串相等,如果它们的内容是平等的,所以你可以这样做:

NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil]; 
BOOL containsString2 = [set containsObject:@"String 2"]; 

使用的NSPredicate这里是矫枉过正,因为NSSet已经有一个-member:方法和-containsObject:方法。

+11

严格来说,如果字符串的内容相同,那么字符串是不相同的(在ANSI C的意义上)。如果指针值相等,则字符串相等。不过,确实你不需要谓词,因为'-member:'和' - containsObject:'方法不会比较对象,而是调用-isEqual:方法 - 在NSStrings的情况下,它实际上会比较对象的内容,而不是对象本身。 – KPM

+10

@KPM除了这不是ANSI C,这是Objective-C,其中'NSString'类已经重写了'-isEqual:'方法来对两个字符串进行类似strcmp的比较。所以严格来说,如果内容相同,两个字符串是相等的。 (我不是在说同一性,这是你得到的两个指针是一样的) –

1
NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil]; 
BOOL containsString2 = [set containsObject:@"String 2"];

可能会或可能无法正常工作。编译器可能会或可能不会为同创建不同的对象@“”字符串,所以我宁愿符合项目谓语做到这一点:

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