iOS Developer Library

Developer

Foundation Framework Reference NSSet Class Reference

Options
Deployment Target:

On This Page
Language:

NSSet

Inheritance


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later.

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.

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

    Declaration

    Swift

    convenience init(array array: [AnyObject])

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    - (instancetype)initWithObjects:(id)firstObj, 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.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    init(objects objects: UnsafePointer<AnyObject?>, count cnt: Int)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    convenience init(set set: Set<NSObject>)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    convenience init(set set: Set<NSObject>, copyItems flag: Bool)

    Objective-C

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

    Parameters

    set

    A set containing objects to add to the new set.

    flag

    If YEStrue, 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 NOfalse, 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 YEStrue for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NOfalse the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • init() - init Designated Initializer

    Initializes a newly allocated set.

    Declaration

    Swift

    init()

    Objective-C

    - (instancetype)init

    Return Value

    A set.

    Discussion

    This method is a designated initializer of NSSet.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • count count Property

    The number of members in the set. (read-only)

    Declaration

    Swift

    var count: Int { get }

    Objective-C

    @property(readonly) NSUInteger count

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • An array containing the set’s members, or an empty array if the set has no members. (read-only)

    Declaration

    Swift

    var allObjects: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *allObjects

    Discussion

    The order of the objects in the array is undefined.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func anyObject() -> AnyObject?

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func containsObject(_ anObject: AnyObject) -> Bool

    Objective-C

    - (BOOL)containsObject:(id)anObject

    Parameters

    anObject

    The object for which to test membership of the set.

    Return Value

    YEStrue if anObject is present in the set, otherwise NOfalse.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – member:

  • 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.

    Declaration

    Swift

    func filteredSetUsingPredicate(_ predicate: NSPredicate) -> Set<NSObject>

    Objective-C

    - (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)

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 3.0 and later.

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

    Declaration

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Determines whether the set contains an object equal to a given object, and returns that object if it is present.

    Declaration

    Swift

    func member(_ object: AnyObject) -> AnyObject?

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func objectEnumerator() -> NSEnumerator

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    nextObject (NSEnumerator)

  • Executes a given Block using each object in the set.

    Declaration

    Swift

    func enumerateObjectsUsingBlock(_ block: (AnyObject!, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (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 YEStrue 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    func enumerateObjectsWithOptions(_ opts: NSEnumerationOptions, usingBlock block: (AnyObject!, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (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 YEStrue 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    func objectsPassingTest(_ predicate: (AnyObject!, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject>

    Objective-C

    - (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 YEStrue 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    func objectsWithOptions(_ opts: NSEnumerationOptions, passingTest predicate: (AnyObject!, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject>

    Objective-C

    - (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 YEStrue 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    func isSubsetOfSet(_ otherSet: Set<NSObject>) -> Bool

    Objective-C

    - (BOOL)isSubsetOfSet:(NSSet *)otherSet

    Parameters

    otherSet

    The set with which to compare the receiving set.

    Return Value

    YEStrue if every object in the receiving set is also present in otherSet, otherwise NOfalse.

    Discussion

    Object equality is tested using isEqual:.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func intersectsSet(_ otherSet: Set<NSObject>) -> Bool

    Objective-C

    - (BOOL)intersectsSet:(NSSet *)otherSet

    Parameters

    otherSet

    The set with which to compare the receiving set.

    Return Value

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

    Discussion

    Object equality is tested using isEqual:.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Compares the receiving set to another set.

    Declaration

    Swift

    func isEqualToSet(_ otherSet: Set<NSObject>) -> Bool

    Objective-C

    - (BOOL)isEqualToSet:(NSSet *)otherSet

    Parameters

    otherSet

    The set with which to compare the receiving set.

    Return Value

    YEStrue if the contents of otherSet are equal to the contents of the receiving set, otherwise NOfalse.

    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:.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – intersectsSet:
    isEqual: (NSObject protocol)
    – isSubsetOfSet:

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

    Declaration

    Swift

    func valueForKey(_ key: String) -> AnyObject

    Objective-C

    - (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).

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func setValue(_ value: AnyObject?, forKey key: String)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func sortedArrayUsingDescriptors(_ sortDescriptors: [AnyObject]) -> [AnyObject]

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Raises an exception.

    Declaration

    Swift

    func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options options: NSKeyValueObservingOptions, context context: UnsafeMutablePointer<Void>)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Raises an exception.

    Declaration

    Swift

    func removeObserver(_ observer: NSObject, forKeyPath keyPath: String, context context: UnsafeMutablePointer<Void>)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Raises an exception.

    Declaration

    Swift

    func removeObserver(_ observer: NSObject, forKeyPath keyPath: String)

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • A string that represents the contents of the set, formatted as a property list. (read-only)

    Declaration

    Swift

    var description: String { get }

    Objective-C

    @property(readonly, copy) NSString *description

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Swift

    func descriptionWithLocale(_ locale: AnyObject?) -> String

    Objective-C

    - (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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    – description