NSArray objectEnumerator
- (NSEnumerator *)objectEnumerator
Return Value
An enumerator object that lets you access each object in the array, in order, from the element at the lowest index upwards.
Discussion of [NSArray objectEnumerator]
Returns an enumerator object that lets you access each object in the array, in order, starting with the element at index 0, as in:
NSEnumerator *enumerator = [myArray objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject]) {
/* code to act on each element as it is returned */
}
Special Considerations
When you use this method with mutable subclasses of NSArray, you must not modify the array during enumeration.
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.
NSArray objectEnumerator example.
NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
// do something with object
}
id object;
while (object = [e nextObject]) {
// do something with object
}
Example of [NSArray objectEnumerator].
NSScreen *screen = nil;
@autoreleasepool{
NSEnumerator *screenEnumerator = [[NSScreen screens] objectEnumerator];
while ((screen = [screenEnumerator nextObject]) && !NSMouseInRect(aPoint, screen.frame, NO));
[screen retain]; // Ensure screen sticks around past return; only under MRR
}
return [screen autorelease];
@autoreleasepool{
NSEnumerator *screenEnumerator = [[NSScreen screens] objectEnumerator];
while ((screen = [screenEnumerator nextObject]) && !NSMouseInRect(aPoint, screen.frame, NO));
[screen retain]; // Ensure screen sticks around past return; only under MRR
}
return [screen autorelease];
NSArray objectEnumerator example.
NSMutableArray *numberSort =[[NSMutableArray alloc] init];
while ((key = [enumerator nextObject])) {
//(NSNumber *)integer = [key integerValue];
[numberSort addObject:[NSNumber numberWithInt:[key intValue]]];
// code that uses the returned key
}
NSArray *stringSort = [numberSort sortedArrayUsingSelector:@selector(compare:)];
enumerator = [stringSort objectEnumerator];
NSNumber *intKey;
NSMutableArray *backToString =[[NSMutableArray alloc] init];
while ((intKey = [enumerator nextObject])) {
//(NSNumber *)integer = [key integerValue];
[backToString addObject:[intKey stringValue]];
// code that uses the returned key
while ((key = [enumerator nextObject])) {
//(NSNumber *)integer = [key integerValue];
[numberSort addObject:[NSNumber numberWithInt:[key intValue]]];
// code that uses the returned key
}
NSArray *stringSort = [numberSort sortedArrayUsingSelector:@selector(compare:)];
enumerator = [stringSort objectEnumerator];
NSNumber *intKey;
NSMutableArray *backToString =[[NSMutableArray alloc] init];
while ((intKey = [enumerator nextObject])) {
//(NSNumber *)integer = [key integerValue];
[backToString addObject:[intKey stringValue]];
// code that uses the returned key