When is NSEnumerator finished?

557 Views Asked by At

How do we know when enumeration is finished? The docs say: the return value of

nextObject

is nil when all objects have been enumerated. I was hoping to implement some "delegate-like" behavior whereby ...

if (nextObject == nil) { 
    do something because we're done!
}

But I see there is no such thing as:

enumerationDidFinish:

where in the following block could I check for the enumerator to be complete?

NSArray *anArray = // ... ;
NSEnumerator *enumerator = [anArray objectEnumerator];
id object;

while ((object = [enumerator nextObject])) {
    // do something with object...
}
5

There are 5 best solutions below

2
On BEST ANSWER

When the while loop finishes, you know the enumeration is complete. You could call the delegate method then.

0
On

Just put your code after the whole while block.

Then when the enumeration is done, it will execute, and you will know it has reached the end.

0
On

The enumerator finishes when the value returned from nextObject is nil

0
On

How about immediatley after the while() loop. When nextObject returns nil, the enumeration is complete and the loop condition fails, continuing execution immediately after the loop body.

0
On

Since if the returned "object" is nil, the while loop won't continue execution in the body, it will break to the end of the loop, putting whatever you want to do with your object there would be a good idea.