samfu_1
samfu_1

Reputation: 1160

When is NSEnumerator finished?

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...
}

Upvotes: 2

Views: 547

Answers (5)

Edward Seshoka
Edward Seshoka

Reputation: 49

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.

Upvotes: 0

Barry Wark
Barry Wark

Reputation: 107774

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.

Upvotes: 2

Jacob Relkin
Jacob Relkin

Reputation: 163318

The enumerator finishes when the value returned from nextObject is nil

Upvotes: 2

Chris Cooper
Chris Cooper

Reputation: 17594

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.

Upvotes: 2

Tom Dalling
Tom Dalling

Reputation: 24145

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

Upvotes: 3

Related Questions