iOS Developer Library — Pre-Release

Developer

Foundation Framework Reference NSEnumerator Class Reference

Options
Deployment Target:

On This Page
Language:

NSEnumerator

Inheritance


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later.

NSEnumerator is an abstract class, instances of whose subclasses enumerate collections of other objects, such as arrays and dictionaries.

All creation methods are defined in the collection classes—such as NSArray, NSSet, and NSDictionary—which provide special NSEnumerator objects with which to enumerate their contents. For example, NSArray has two methods that return an NSEnumerator object: objectEnumerator and reverseObjectEnumerator. NSDictionary also has two methods that return an NSEnumerator object: keyEnumerator and objectEnumerator. These methods let you enumerate the contents of a dictionary by key or by value, respectively.

You send nextObject repeatedly to a newly created NSEnumerator object to have it return the next object in the original collection. When the collection is exhausted, nil is returned. You cannot “reset” an enumerator after it has exhausted its collection. To enumerate a collection again, you need a new enumerator.

The enumerator subclasses used by NSArray, NSDictionary, and NSSet retain the collection during enumeration. When the enumeration is exhausted, the collection is released.

  • The array of unenumerated objects. (read-only)

    Declaration

    Swift

    var allObjects: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *allObjects

    Discussion

    This array contains all the remaining objects in the enumerated collection. It does not contain objects that have already been enumerated with previous nextObject messages.

    Accessing this property exhausts the enumerator’s collection so that subsequent invocations of nextObject return nil.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns the next object from the collection being enumerated.

    Declaration

    Swift

    func nextObject() -> AnyObject?

    Objective-C

    - (id)nextObject

    Return Value

    The next object from the collection being enumerated, or nil when all objects have been enumerated.

    Discussion

    The following code illustrates how this method works using an array:

    • NSArray *anArray = // ... ;
    • NSEnumerator *enumerator = [anArray objectEnumerator];
    • id object;
    • while ((object = [enumerator nextObject])) {
    • // do something with object...
    • }

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.