Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Tuesday, March 4, 2008

Searching a complex ArrayCollection in Flex and how I hate the damn IViewCursor

I'll preface this post as I do many by stating that I'm relatively new to Actionscript and Flex so I'm not really sure if the code I present here is a solution or a hack. In either case it works.

While building a 'Save Game' feature for my Sudoku game I was came across a situation where I needed to search an existing ArrayCollection for the ID of a previously saved game. I knew what the ID was but just needed to locate it's index position in the collection. While looking at the Flex documentation I noticed that the ArrayCollection component has a nice method called getItemIndex. However this wasn't going to be any use to me because getItemIndex only finds exact matches of an entire object and I needed to match only a single value. This lead me to look into the use of an IViewCursor.

While creating a cursor to access and manipulate and ArrayCollection seems like an intuitive concept trying to understand how to use it frankly makes my head spin. So instead I just wrote a simple function. If someone can tell me why using an IViewCursor is better or easier than the following function I would like to hear it ( and see an example ).

// returns the index position of object with matching usid value
private function usidSearch( usid:Number, coll:ArrayCollection ):Number
{
var o:Object;
for ( var i:Number = 0; i<coll.length; i++){
o = coll.getItemAt(i);
if( o.usid == usid) return i;
}
return -1;
}

3 comments:

  1. Cursors are used to entertain encapsulation. However, in my application, which is huge, cursors doesn't work.

    When I try to add event listener, it doesn't set afterlast to true after movenext() moves to the end of the collection. You will get the same result if you replace event listener with a function.

    ReplyDelete
  2. Would a filter function work here ?

    ReplyDelete
  3. @ogrampowell

    A filter function serves a different purpose. If you want to limit the number of records shown in an ArrayCollection that is being used as a dataProvider for say a DataGrid then a filterFunction serves this purpose. But if you want to find the index of a record within the array collection a filter function wouldn't work as it would physically alters the collection to contain only matching results.

    ReplyDelete

Thank you for the comments.