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:
-
var cursor:IViewCursor = myCollection.createCursor();
-
-
while (!cursor.afterLast) {
-
trace(cursor.current);
-
// forget this line and you're big trouble son!
-
cursor.moveNext();
-
}
The for-loop equivalent looks like this:
-
for (var cursor:IViewCursor = myCollection.createCursor(); !cursor.afterLast; cursor.moveNext()) {
-
trace(cursor.current);
-
}
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
Christophe Herreman is a software developer living in Belgium. He's working on high-end Flex and AIR solutions at
August 7th, 2008 at 12:07 pm
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)
}
August 7th, 2008 at 2:16 pm
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.