Exercise 3

Hello,

For the answer to exercise 3, I’m not too sure what can be the right answer for the simple (not fast) iterator. I think that if we can cache in the NSEnumerator’s object the scanned object value, then we should be able, when calling the nextObject method, to ask the array at which index is the scanned object(with indexOfObjectIdenticalTo:) and from there to pick up the next one.

This solutions has a few problems however:
[ul]
[li]If you have more than one time the same object in the array you will trigger infinite loop.[/li]
[li]If at each iteration step you add object after the actual position you also trigger infinite loop.[/li]
[li]You can skip some object if you a twice the same object in the array and you remove the first one during the enumration.[/li]
[li]You have problem when your code is multithreaded (thread A remove the actual object before thread B is able to find its position).[/li]
[li]Possibly some other cases I cannot think about[/li][/ul]

Has someone other ideas to answer the question (with less problems)? What do you think about my version?

CU Jérôme

Interesting approach - I didn’t think of caching the current object, and using that to figure out where you are in the sequence. The duplicate object problem is probably the biggest stopping point.

Back In The Mists Of Time I wrote 2-D array-like data structure which supported mutating when iterating, and that was a pretty big pain, which makes me appreciate non-mutable-iteration data structures from the API-wrtiers’ point of view. What I did for that was the iterator kept a “current index”, and then adjusted that index based on changes to the array.

If an element was inserted before the index, bump up the index so that it points in the same place (and make the contract plain that mutations on indices that have already been scanned over won’t be included in the iteration) Similarly, if objects were removed before the index, the index was decremented an appropriate number of times.

You can imagine the off-by-one / obiwan / fencepost errors that had to be verified.

Cheers,
++md