NSString lookup in NSSet
How may I find a certain string (value) in an NSSet?
Must this be done using predicates? If so, how?NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:[[[NSString alloc] initWithForm开发者_JAVA百科at:@"String %d", 1] autorelease]];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 2] autorelease]];
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 3] autorelease]];
Now I want to check if 'String 2' exists in the set.
Strings are equal if their contents are equal, so you can just do:
NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil];
BOOL containsString2 = [set containsObject:@"String 2"];
Using an NSPredicate
here is overkill, because NSSet
already has a -member:
method and a -containsObject:
method.
From 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 contains some more information on using predicates. Finally Apple's BNF guide for predicates contains information on all operations one might need.
might member: work here?
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"];
May or may not work. The compiler may or may not create different objects for the same @"" string, so I would rather do it with MATHCES predicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"String 2"];
精彩评论