views:

502

answers:

2

I have overcome a problem, but my solution seems really inefficient and clunky. Please consider this problem:

I have an array collection with articles in.

This array collection is filtered to a currently selected article category. 

There is a cursor bound to a view that shows the current article.

When a category is deleted I need to delete orphened articles, I can't use the cursor or collection without affecting the views as they are bound. 

I can itterate over the source, but if I delete (splice) from the source I have to break and start again, as all the articles indexes change, even when using for each.

This seems like a really inefficient way of doing things, and I'm sure there is a better way to do it, eithe by using another itterator on the same source, or unbinding the views unill I have finished updating, etc

Please let me know if I am missing a trick as I'm sure this is a really common problem/issue.

Thanks

Rob

p.s. Wrote this on my iPhone. Sorry for any mistakes!

A: 

Simplest solution would probably be to just save the indexes you need to remove in a temporary array. Then after you've iterated through the collection, go back and just remove the items in the temporary array.

But from what I can gather, you should probably use a hash (Object) or something instead of an array structure.

CookieOfFortune
I tried that, but as soon as you remove one item (splice) the other indexes are no longer correct!
robmcm
sort indices, remove from the end. Once again, think about using a different data structure.
CookieOfFortune
Just a quick question, could you show me an example of using objects, and how you could use something like an array collection on it (or implement an iViewCollection)
robmcm
+1  A: 

Run the loop backwards.

So, instead of, say:

var len:int = arr.length;
for(var i:int = 0; i < len; i++) {
    if(some condition) {
        arr.splice(i,1);
    }
}

do this:

for(var i:int = arr.length - 1; i >= 0; i--) {
    if(some condition) {
        arr.splice(i,1);
    }
}
Juan Pablo Califano
silly micro-optimization: do a predecrement instead of a post for a few milliseconds of boost
grapefrukt
That seems so obvious now... thanks!
robmcm