NSSet Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 2.0 and later.
Companion guide
Declared in
NSKeyValueCoding.h
NSKeyValueObserving.h
NSPredicate.h
NSSet.h
NSSortDescriptor.h
Related sample code

Overview

The NSSet, NSMutableSet, and NSCountedSet classes declare the programmatic interface to an unordered collection of objects.

NSSet declares the programmatic interface for static sets of distinct objects. You establish a static set’s entries when it’s created, and thereafter the entries can’t be modified. NSMutableSet, on the other hand, declares a programmatic interface for dynamic sets of distinct objects. A dynamic—or mutable—set allows the addition and deletion of entries at any time, automatically allocating memory as needed.

You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.

NSSet is “toll-free bridged” with its Core Foundation counterpart, CFSetRef. See “Toll-Free Bridging” for more information on toll-free bridging.

Subclassing Notes

There should be little need of subclassing. If you need to customize behavior, it is often better to consider composition instead of subclassing.

Methods to Override

In a subclass, you must override all of its primitive methods:

Alternatives to Subclassing

Before making a custom class of NSSet, investigate NSHashTable and the corresponding Core Foundation type, CFSet Reference. Because NSSet and CFSet are “toll-free bridged,” you can substitute a CFSet object for a NSSet object in your code (with appropriate casting). Although they are corresponding types, CFSet and NSSet do not have identical interfaces or implementations, and you can sometimes do things with CFSet that you cannot easily do with NSSet.

If the behavior you want to add supplements that of the existing class, you could write a category on NSSet. Keep in mind, however, that this category will be in effect for all instances of NSSet that you use, and this might have unintended consequences. Alternatively, you could use composition to achieve the desired behavior.

Adopted Protocols

NSCoding
NSCopying
NSMutableCopying
NSFastEnumeration

Tasks

Creating a Set

Initializing a Set

Counting Entries

Accessing Set Members

Comparing Sets

Creating a Sorted Array

Key-Value Observing

Describing a Set

Class Methods

set

Creates and returns an empty set.

+ (instancetype)set
Return Value

A new empty set.

Discussion

This method is declared primarily for the use of mutable subclasses of NSSet.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSSet.h

setWithArray:

Creates and returns a set containing a uniqued collection of the objects contained in a given array.

+ (instancetype)setWithArray:(NSArray *)array
Parameters
array

An array containing the objects to add to the new set. If the same object appears more than once in array, it is added only once to the returned set. Each object receives a retain message as it is added to the set.

Return Value

A new set containing a uniqued collection of the objects contained in array.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSSet.h

setWithObject:

Creates and returns a set that contains a single given object.

+ (instancetype)setWithObject:(id)object
Parameters
object

The object to add to the new set. object receives a retain message after being added to the set.

Return Value

A new set that contains a single member, object.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setWithObjects:

Creates and returns a set containing the objects in a given argument list.

+ (instancetype)setWithObjects:(id)firstObj, ...
Parameters
firstObj

The first object to add to the new set.

firstObj, ...

A comma-separated list of objects, ending with nil, to add to the new set. If the same object appears more than once in the list of objects, it is added only once to the returned set. Each object receives a retain message as it is added to the set.

Return Value

A new set containing the objects in the argument list.

Discussion

As an example, the following code excerpt creates a set containing three different types of elements (assuming aPath exits):

NSSet *mySet;
NSData *someData = [NSData dataWithContentsOfFile:aPath];
NSValue *aValue = [NSNumber numberWithInteger:5];
NSString *aString = @"a string";
 
mySet = [NSSet setWithObjects:someData, aValue, aString, nil];
Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setWithObjects:count:

Creates and returns a set containing a specified number of objects from a given C array of objects.

+ (instancetype)setWithObjects:(const id [])objects count:(NSUInteger)cnt
Parameters
objects

A C array of objects to add to the new set. If the same object appears more than once in objects, it is added only once to the returned set. Each object receives a retain message as it is added to the set.

cnt

The number of objects from objects to add to the new set.

Return Value

A new set containing cnt objects from the list of objects specified by objects.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setWithSet:

Creates and returns a set containing the objects from another set.

+ (instancetype)setWithSet:(NSSet *)set
Parameters
set

A set containing the objects to add to the new set. Each object receives a retain message as it is added to the new set.

Return Value

A new set containing the objects from set.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

Instance Methods

addObserver:forKeyPath:options:context:

Raises an exception.

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
Parameters
observer

The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context:.

keyPath

The key path, relative to the set, of the property to observe. This value must not be nil.

options

A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications. For possible values, see NSKeyValueObservingOptions.

context

Arbitrary data that is passed to observer in observeValueForKeyPath:ofObject:change:context:.

Special Considerations

NSSet objects are not observable, so this method raises an exception when invoked on an NSSet object. Instead of observing a set, observe the unordered to-many relationship for which the set is the collection of related objects.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyValueObserving.h

allObjects

Returns an array containing the set’s members, or an empty array if the set has no members.

- (NSArray *)allObjects
Return Value

An array containing the set’s members, or an empty array if the set has no members. The order of the objects in the array isn’t defined.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSSet.h

anyObject

Returns one of the objects in the set, or nil if the set contains no objects.

- (id)anyObject
Return Value

One of the objects in the set, or nil if the set contains no objects. The object returned is chosen at the set’s convenience—the selection is not guaranteed to be random.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

containsObject:

Returns a Boolean value that indicates whether a given object is present in the set.

- (BOOL)containsObject:(id)anObject
Parameters
anObject

The object for which to test membership of the set.

Return Value

YES if anObject is present in the set, otherwise NO.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSSet.h

count

Returns the number of members in the set.

- (NSUInteger)count
Return Value

The number of members in the set.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSSet.h

description

Returns a string that represents the contents of the set, formatted as a property list.

- (NSString *)description
Return Value

A string that represents the contents of the set, formatted as a property list.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

descriptionWithLocale:

Returns a string that represents the contents of the set, formatted as a property list.

- (NSString *)descriptionWithLocale:(id)locale
Parameters
locale

On iOS and OS X v10.5 and later, either an instance of NSDictionary or an NSLocale object may be used for locale.On OS X v10.4 and earlier it must be an instance of NSDictionary.

Return Value

A string that represents the contents of the set, formatted as a property list.

Discussion

This method sends each of the set’s members descriptionWithLocale: with locale passed as the sole parameter. If the set’s members do not respond to descriptionWithLocale:, this method sends description instead.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

enumerateObjectsUsingBlock:

Executes a given Block using each object in the set.

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, BOOL *stop))block
Parameters
block

The Block to apply to elements in the set.

The Block takes two arguments:

obj

The element in the set.

stop

A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

The Block returns a Boolean value that indicates whether obj passed the test.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSSet.h

enumerateObjectsWithOptions:usingBlock:

Executes a given Block using each object in the set, using the specified enumeration options.

- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, BOOL *stop))block
Parameters
opts

A bitmask that specifies the options for the enumeration.

block

The Block to apply to elements in the set.

The Block takes two arguments:

obj

The element in the set.

stop

A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

The Block returns a Boolean value that indicates whether obj passed the test.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSSet.h

filteredSetUsingPredicate:

Evaluates a given predicate against each object in the receiving set and returns a new set containing the objects for which the predicate returns true.

- (NSSet *)filteredSetUsingPredicate:(NSPredicate *)predicate
Parameters
predicate

A predicate.

Return Value

A new set containing the objects in the receiving set for which predicate returns true.

Discussion

The following example illustrates the use of this method.

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)
Availability
  • Available in iOS 3.0 and later.
Declared In
NSPredicate.h

init

Initializes a newly allocated set.

- (instancetype)init
Return Value

A set.

Discussion

This method is a designated initializer of NSSet.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSSet.h

initWithArray:

Initializes a newly allocated set with the objects that are contained in a given array.

- (instancetype)initWithArray:(NSArray *)array
Parameters
array

An array of objects to add to the new set. If the same object appears more than once in array, it is represented only once in the returned set. Each object receives a retain message as it is added to the set.

Return Value

An initialized set with the contents of array. The returned set might be different than the original receiver.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

initWithObjects:

Initializes a newly allocated set with members taken from the specified list of objects.

- (instancetype)initWithObjects:(id)firstObj, ...
Parameters
firstObj

The first object to add to the new set.

firstObj, ...

A comma-separated list of objects, ending with nil, to add to the new set. If the same object appears more than once in the list, it is represented only once in the returned set. Each object receives a retain message as it is added to the set

Return Value

An initialized set containing the objects specified in the parameter list. The returned set might be different than the original receiver.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

initWithObjects:count:

Initializes a newly allocated set with a specified number of objects from a given C array of objects.

- (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt
Parameters
objects

A C array of objects to add to the new set. If the same object appears more than once in objects, it is added only once to the returned set. Each object receives a retain message as it is added to the set.

cnt

The number of objects from objects to add to the new set.

Return Value

An initialized set containing cnt objects from the list of objects specified by objects. The returned set might be different than the original receiver.

Discussion

This method is a designated initializer for NSSet.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

initWithSet:

Initializes a newly allocated set and adds to it objects from another given set.

- (instancetype)initWithSet:(NSSet *)set
Parameters
set

A set containing objects to add to the receiving set. Each object is retained as it is added.

Return Value

An initialized objects set containing the objects from set. The returned set might be different than the original receiver.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

initWithSet:copyItems:

Initializes a newly allocated set and adds to it members of another given set.

- (instancetype)initWithSet:(NSSet *)set copyItems:(BOOL)flag
Parameters
set

A set containing objects to add to the new set.

flag

If YES, each object in set receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned set.

If NO, then in a managed memory environment each object in set simply receives a retain message when it is added to the returned set.

Return Value

An initialized set that contains the members of set. The returned set might be different than the original receiver.

Discussion

After an immutable s has been initialized in this way, it cannot be modified.

The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

intersectsSet:

Returns a Boolean value that indicates whether at least one object in the receiving set is also present in another given set.

- (BOOL)intersectsSet:(NSSet *)otherSet
Parameters
otherSet

The set with which to compare the receiving set.

Return Value

YES if at least one object in the receiving set is also present in otherSet, otherwise NO.

Discussion

Object equality is tested using isEqual:.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

isEqualToSet:

Compares the receiving set to another set.

- (BOOL)isEqualToSet:(NSSet *)otherSet
Parameters
otherSet

The set with which to compare the receiving set.

Return Value

YES if the contents of otherSet are equal to the contents of the receiving set, otherwise NO.

Discussion

Two sets have equal contents if they each have the same number of members and if each member of one set is present in the other. Object equality is tested using isEqual:.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSSet.h

isSubsetOfSet:

Returns a Boolean value that indicates whether every object in the receiving set is also present in another given set.

- (BOOL)isSubsetOfSet:(NSSet *)otherSet
Parameters
otherSet

The set with which to compare the receiving set.

Return Value

YES if every object in the receiving set is also present in otherSet, otherwise NO.

Discussion

Object equality is tested using isEqual:.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

makeObjectsPerformSelector:

Sends a message specified by a given selector to each object in the set.

- (void)makeObjectsPerformSelector:(SEL)aSelector
Parameters
aSelector

A selector that specifies the message to send to the members of the set. The method must not take any arguments. It should not have the side effect of modifying the set. This value must not be NULL.

Discussion

The message specified by aSelector is sent once to each member of the set. This method raises an NSInvalidArgumentException if aSelector is NULL.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

makeObjectsPerformSelector:withObject:

Sends a message specified by a given selector to each object in the set.

- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument
Parameters
aSelector

A selector that specifies the message to send to the set's members. The method must take a single argument of type id. The method should not, as a side effect, modify the set. The value must not be NULL.

argument

The object to pass as an argument to the method specified by aSelector.

Discussion

The message specified by aSelector is sent, with argument as the argument, once to each member of the set. This method raises an NSInvalidArgumentException if aSelector is NULL.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

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

objectEnumerator

Returns an enumerator object that lets you access each object in the set.

- (NSEnumerator *)objectEnumerator
Return Value

An enumerator object that lets you access each object in the set.

Discussion

The following code fragment illustrates how you can use this method.

NSEnumerator *enumerator = [mySet objectEnumerator];
id value;
 
while ((value = [enumerator nextObject])) {
    /* code that acts on the set’s values */
}

When this method is used with mutable subclasses of NSSet, your code shouldn’t modify the set during enumeration. If you intend to modify the set, use the allObjects method to create a “snapshot” of the set’s members. Enumerate the snapshot, but make your modifications to the original set.

Special Considerations

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on OS X v10.5 and later and iOS 2.0 and later.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSSet.h

objectsPassingTest:

Returns a set of object that pass a test in a given Block.

- (NSSet *)objectsPassingTest:(BOOL (^)(id obj, BOOL *stop))predicate
Parameters
predicate

The block to apply to elements in the array.

The block takes three arguments:

obj

The element in the set.

stop

A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

The Block returns a Boolean value that indicates whether obj passed the test.

Return Value

An NSSet containing objects that pass the test.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSSet.h

objectsWithOptions:passingTest:

Returns a set of object that pass a test in a given Block, using the specified enumeration options.

- (NSSet *)objectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, BOOL *stop))predicate
Parameters
opts

A bitmask that specifies the options for the enumeration.

predicate

The Block to apply to elements in the set.

The Block takes two arguments:

obj

The element in the set.

stop

A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

The Block returns a Boolean value that indicates whether obj passed the test.

Return Value

An NSSet containing objects that pass the test.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSSet.h

removeObserver:forKeyPath:

Raises an exception.

- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
Parameters
observer

The object to remove as an observer.

keyPath

A key-path, relative to the set, for which observer is registered to receive KVO change notifications. This value must not be nil.

Special Considerations

NSSet objects are not observable, so this method raises an exception when invoked on an NSSet object. Instead of observing a set, observe the unordered to-many relationship for which the set is the collection of related objects.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyValueObserving.h

removeObserver:forKeyPath:context:

Raises an exception.

- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(void *)context
Parameters
observer

The object to remove as an observer.

keyPath

A key-path, relative to the set, for which observer is registered to receive KVO change notifications. This value must not be nil.

context

Arbitrary data that is passed to observer in observeValueForKeyPath:ofObject:change:context:.

Special Considerations

NSSet objects are not observable, so this method raises an exception when invoked on an NSSet object. Instead of observing a set, observe the unordered to-many relationship for which the set is the collection of related objects.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSKeyValueObserving.h

setByAddingObject:

Returns a new set formed by adding a given object to the receiving set.

- (NSSet *)setByAddingObject:(id)anObject
Parameters
anObject

The object to add to the set.

Return Value

A new set formed by adding anObject to the receiving set.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setByAddingObjectsFromArray:

Returns a new set formed by adding the objects in a given array to the receiving set.

- (NSSet *)setByAddingObjectsFromArray:(NSArray *)other
Parameters
other

The array of objects to add to the set.

Return Value

A new set formed by adding the objects in other to the receiving set.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setByAddingObjectsFromSet:

Returns a new set formed by adding the objects in a given set to the receiving set.

- (NSSet *)setByAddingObjectsFromSet:(NSSet *)other
Parameters
other

The set of objects to add to the receiving set.

Return Value

A new set formed by adding the objects in other to the receiving set.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSSet.h

setValue:forKey:

Invokes setValue:forKey: on each of the set’s members.

- (void)setValue:(id)value forKey:(NSString *)key
Parameters
value

The value for the property identified by key.

key

The name of one of the properties of the set's members.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyValueCoding.h

sortedArrayUsingDescriptors:

Returns an array of the set’s content sorted as specified by a given array of sort descriptors.

- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors
Parameters
sortDescriptors

An array of NSSortDescriptor objects.

Return Value

An NSArray containing the set’s content sorted as specified by sortDescriptors.

Discussion

The first descriptor specifies the primary key path to be used in sorting the set’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSSortDescriptor.h

valueForKey:

Return a set containing the results of invoking valueForKey: on each of the receiving set's members.

- (id)valueForKey:(NSString *)key
Parameters
key

The name of one of the properties of the receiving set's members.

Return Value

A set containing the results of invoking valueForKey: (with the argument key) on each of the receiving set's members.

Discussion

The returned set might not have the same number of members as the receiving set. The returned set will not contain any elements corresponding to instances of valueForKey: returning nil (note that this is in contrast with NSArray’s implementation, which may put NSNull values in the arrays it returns).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyValueCoding.h