NSSet
An NSSet is an unordered collection of unique objects. Use a set when you care about whether something is in the collection, not where: tags, visited pages, selected items. Membership tests are fast (hash lookups) no matter how big the set is, whereas [array containsObject:] has to check every element.
Creating sets
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSSet *tags = [NSSet setWithObjects:@"swift", @"ios", @"objc", @"ios", nil];
NSSet *fromArray = [NSSet setWithArray:@[@3, @1, @3, @2, @1]];
NSLog(@"tags: %lu unique", (unsigned long)tags.count); // the duplicate is dropped
NSLog(@"numbers: %lu unique", (unsigned long)fromArray.count);
NSLog(@"has objc? %d", [tags containsObject:@"objc"]);
NSLog(@"has java? %d", [tags containsObject:@"java"]);
// A set has no order: sort it to print it predictably
NSArray *sorted = [fromArray.allObjects sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"sorted: %@", [sorted componentsJoinedByString:@", "]);
}
return 0;
}tags: 3 unique
numbers: 3 unique
has objc? 1
has java? 0
sorted: 1, 2, 3
Uniqueness is decided with isEqual: and hash, so two different string objects with the same text count as one element.
Set operations
Mathematical set operations live on NSMutableSet; they modify the receiver. Make mutable copies to keep the originals:
#import <Foundation/Foundation.h>
NSString *listOf(NSSet *set) {
return [[set.allObjects sortedArrayUsingSelector:@selector(compare:)] componentsJoinedByString:@" "];
}
int main(void) {
@autoreleasepool {
NSSet *anna = [NSSet setWithArray:@[@"chess", @"hiking", @"jazz", @"cooking"]];
NSSet *ben = [NSSet setWithArray:@[@"jazz", @"football", @"cooking"]];
NSMutableSet *both = [anna mutableCopy];
[both intersectSet:ben]; // in both
NSLog(@"shared: %@", listOf(both));
NSMutableSet *either = [anna mutableCopy];
[either unionSet:ben]; // in at least one
NSLog(@"all: %@", listOf(either));
NSMutableSet *onlyAnna = [anna mutableCopy];
[onlyAnna minusSet:ben]; // in anna but not ben
NSLog(@"only Anna: %@", listOf(onlyAnna));
NSLog(@"overlap? %d", [anna intersectsSet:ben]);
NSSet *small = [NSSet setWithObject:@"jazz"];
NSLog(@"{jazz} subset of Ben? %d", [small isSubsetOfSet:ben]);
}
return 0;
}shared: cooking jazz
all: chess cooking football hiking jazz
only Anna: chess hiking
overlap? 1
{jazz} subset of Ben? 1
| Operation | Method | Result |
|---|---|---|
| intersection | intersectSet: |
elements in both |
| union | unionSet: |
elements in either |
| difference | minusSet: |
elements only in the receiver |
| overlap test | intersectsSet: |
YES if any element is shared |
| subset test | isSubsetOfSet: |
YES if every element is in the other set |
NSMutableSet for tracking
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *visits = @[@"/home", @"/about", @"/home", @"/blog", @"/about", @"/home"];
NSMutableSet *seen = [NSMutableSet set];
for (NSString *page in visits) {
if ([seen containsObject:page]) {
NSLog(@"%@ (again)", page);
} else {
[seen addObject:page];
NSLog(@"%@ (first visit)", page);
}
}
[seen removeObject:@"/blog"];
NSLog(@"%lu distinct pages kept", (unsigned long)seen.count);
}
return 0;
}/home (first visit)
/about (first visit)
/home (again)
/blog (first visit)
/about (again)
/home (again)
2 distinct pages kept
Removing duplicates from an array
To deduplicate and keep the original order, use NSOrderedSet, which is both ordered and unique:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *emails = @[@"b@x.io", @"a@x.io", @"b@x.io", @"c@x.io", @"a@x.io"];
NSOrderedSet *unique = [NSOrderedSet orderedSetWithArray:emails];
NSLog(@"in order: %@", [unique.array componentsJoinedByString:@", "]);
NSLog(@"first: %@, index of c: %lu", unique.firstObject, (unsigned long)[unique indexOfObject:@"c@x.io"]);
// NSCountedSet remembers how many times each object was added
NSCountedSet *counted = [NSCountedSet setWithArray:emails];
NSLog(@"b@x.io appears %lu times", (unsigned long)[counted countForObject:@"b@x.io"]);
}
return 0;
}in order: b@x.io, a@x.io, c@x.io
first: b@x.io, index of c: 2
b@x.io appears 2 times
Which collection?
| Need | Use |
|---|---|
| ordered list, duplicates allowed | NSArray |
| lookup by key | NSDictionary |
| fast membership, unique, no order | NSSet |
| unique and ordered | NSOrderedSet |
| unique with counts | NSCountedSet |
Note: Never print a set with
%@and expect a particular order: the order of elements in a set's description depends on hash values and differs between Apple's Foundation and GNUstep.
Test yourself
How many elements does [NSSet setWithArray:@[@1, @1, @2]] have?
- 3
- 2
- 1
- 0
Which method keeps only the elements present in both sets?
- unionSet:
- minusSet:
- intersectSet:
- isSubsetOfSet:
Which class removes duplicates but keeps the original order?
- NSSet
- NSCountedSet
- NSOrderedSet
- NSDictionary