Looping through an IViewCursor with a for-loop

ActionScript, Flash, Flex Add comments

If you've been working with collections in Flex 2 you most likely already ran into an infinite loop when iterating over a collection cursor because you forgot to call the moveNext() method on the cursor. I've been scratching my head a few times the last weeks just because of this and thought the "problem" could easily be solved by using a for-loop instead of a while-loop to iterate over the cursor.

Here's an example of a while-loop iterating over an IViewCursor:

Actionscript:
  1. var cursor:IViewCursor = myCollection.createCursor();
  2.  
  3. while (!cursor.afterLast) {
  4.   trace(cursor.current);
  5.   // forget this line and you're big trouble son!
  6.   cursor.moveNext();
  7. }

The for-loop equivalent looks like this:

Actionscript:
  1. for (var cursor:IViewCursor = myCollection.createCursor(); !cursor.afterLast; cursor.moveNext()) {
  2.   trace(cursor.current);
  3. }

In my opinion the for-loop approach looks a lot cleaner and is less error-prone than the while-loop. It also has fewer lines of code and will probably save some resources since the cursor is defined in the for-loop.


Add to Bloglines - Digg This! - del.icio.us - Stumble It! - Twit This! - Technorati links - Share on Facebook - Feedburner
 

2 Responses to “Looping through an IViewCursor with a for-loop”

  1. Howard Fore Says:

    What’s the advantage of using an IViewCursor in the for loop instead of the for-each structure, like so:

    for each (var myObject:Object in myCollection)
    {
    trace(myObject)
    }

  2. Christophe Says:

    Hi Howard, with a view cursor you have control over the way you loop through the collection. A for each loop might be bit faster though, haven’t tested.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login