Let's say you have all of your users in "usersCollection" which is an ArrayCollection. A user object may contain things like "firstNamename","lastName", "email", "address" and so on. Now, what if you need to find a specific user like "John Rambo". Then you'll need to search both the first and last name fields. You could of course traverse the entire collection using a loop, checking every iteration. Hang on, there is a faster way using a cursor (it's kinda lika a struct pointer if you're a C person).
First you need to sort the collection
var mySort:Sort = new Sort();mySort.fields = [new SortField('lastname')];usersCollection.sort = mySort;usersCollection.refresh();
Then we create the cursor, pointing to the first item in the collection at init.
var cursor:iViewCursor = usersCollection.createCursor;
Now, we need to search both first and last name, so we create a searchobject.
var sObj:Object = {firstname:"John",lastname:"Rambo"};
We are now ready to do the actual search by using the findAny method of the cursor.
if(cursor.findAny(sObj)){ //We found him}else{ //John Rambo is lost again}
In order to get to the user we found we utilize the current property of the cursor.
var foundUser:Object = cursor.current;
Do keep in mind that the cursor is now pointing to the user found, so if we want the next user in the list we can simply go "cursor.moveNext()"
Why should you use this method? It's more flexible, it's faster and uses less resources than the traditional iterative loop approach.
1 comment:
WONDERFUL. huge help. I wonder why the cursor isn't talked about more.
Post a Comment