How to quickly iterate over the children of a container

Display object containers (like SPSprite) can have numerous children. It's a common mission to do something with all of those children. This is, of course, done with a loop. Most of you will already have used a code like the following:

for (int i=0; i<container.numChildren; ++i)
{
  SPDisplayObject *child = [container childAtIndex:i];
  [child doSomething];
}

However, there's another way to do it. The nice thing about that alternative is that it's not only less code to write, but it's also more efficient, and will thus save your CPU some work. Here's how to do it:

for (SPDisplayObject *child in container)
  [child doSomething];

Not too bad, isn't it?

  tutorials/iterating_over_child_objects.txt · Last modified: 2013/03/05 10:19 by 127.0.0.1
 
Powered by DokuWiki