Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] initWithFormat:@"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.

like image 360
Egil Avatar asked Jul 03 '11 10:07

Egil


1 Answers

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.

like image 120
Dave DeLong Avatar answered Sep 21 '22 07:09

Dave DeLong