NSSet中的NSString查找

时间:2011-07-03 10:21:04

标签: 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]];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 3] autorelease]];

现在我想检查一下是否存在'String 2'。

4 个答案:

答案 0 :(得分:44)

如果字符串的内容相等,则字符串相等,所以您可以这样做:

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

在这里使用NSPredicate是过度的,因为NSSet已经有-member:方法和-containsObject:方法。

答案 1 :(得分:7)

来自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包含有关可能需要的所有操作的信息。

答案 2 :(得分: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

答案 3 :(得分:1)

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"];
相关问题