Next Page > Hide TOC

NSEnumerator Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in Mac 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.

Note: It is not safe to modify a mutable collection while enumerating through it. Some enumerators may currently allow enumeration of a collection that is modified, but this behavior is not guaranteed to be supported in the future.

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
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
Related Sample Code
Declared In
NSEnumerator.h

Next Page > Hide TOC


© 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-02-23)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.