can't remove all images of a sprite-container

I've got a stack of images. Those images are all added to a sprite container:

var container:Sprite = new Sprite();
container.addChild(img);//added in a loop
addChild(container);

Later, when I iterate through the container to remove the images I say:

for(var i:int=0;i<container.numChildren;i++)
{
     var currImg:Sprite = container.getChildAt(i) as Sprite;
     container.removeChild(currImg);
}

Only a part of the images are removed. If I trace container.numChildren I get the correct number of images to be removed. Did someone have the same problem ?

Answers


I've encountered this problem as well. What's actually wrong here is that you're stepping up through the display list AND cutting it down with each iteration. In AVM2 the display list depth is automatically managed in this context, and when you remove a child the rest of the display list depth is adjusted. Anyway, the solution is to wrap it up in a while loop:

while(container.numChildren > 0){
    container.removeChildAt(0);
}

Update Also one note about your code. Try not to cast a new reference to the clip. This will cause issues for the garbage collection process in the flash VM, which is automated and only objects dereferenced or referenced using weak references will be cleaned up. So you can do one of the following:

for(var i:int=0;i<container.numChildren;i++)
{
     var currImg:Sprite = container.getChildAt(i) as Sprite;
     container.removeChild(currImg);
     currImg = null;
}

or

for(var i:int=0;i<container.numChildren;i++)
{
     container.removeChild(Sprite(container.getChildAt(i)));
}

Try removing them in reverse order. It's possible that your're missing removals because you're trying to remove them while in a forward-bound loop.

for(var i:int=container.numChildren;i>=0;i--)
{
     var currImg:Sprite = container.getChildAt(i) as Sprite;
     container.removeChild(currImg);
}

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.