NSEnumerator Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in OS X v10.0 and later.
Companion guide
Declared in
NSEnumerator.h
Related sample code

Overview

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.

Tasks

Getting the Enumerated Objects

Instance Methods

allObjects

Returns an array of objects the receiver has yet to enumerate.

- (NSArray *)allObjects
Return Value

An array of objects the receiver has yet to enumerate.

Discussion

Put another way, the array returned by this method does not contain objects that have already been enumerated with previous nextObject messages.

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSEnumerator.h

nextObject

Returns the next object from the collection being enumerated.

- (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...
}
Availability
  • Available in OS X v10.0 and later.
Declared In
NSEnumerator.h