views:

759

answers:

3

Hi.

I have trouble with deleting all layer's sublayers. I do this manually, but it's unwanted code clutter. I found many topics about this in google, but no answer.

I tried to do something like this:

for(CALayer *layer in rootLayer.sublayers)
{
    [layer removeFromSublayer];
}

but it didn't work.

Also, i tried to clone rootLayer.sublayers into separate NSArray, but result was the same.

Any ideas?

regards, radex

PS. sorry for my English.

Edit:

I thought it works now, but I was wrong. It works good with CALayers, but it doesn't work with CATextLayers. Any ideas?

+1  A: 

The following should work:

for (CALayer *layer in [[rootLayer.sublayers copy] autorelease]) {
    [layer removeFromSuperlayer];
}
Ben Gottlieb
Thanks! Your solution works, and mine would probably too, because the problem was somewhere else.
radex
You have to use a copy of the sub-layers list: otherwise you will end up modifying the list while iterating over it, which is not really really safe.
Laurent Etiemble
A: 

How about using reverse enumeration?

NSEnumerator *enumerator = [rootLayer.sublayers reverseObjectEnumerator];
for(CALayer *layer in enumerator) {
    [layer removeFromSuperlayer];
}

Because the group in sublayers are changed during enumeration, if the order is normal. I would like to know the above code's result.

KatokichiSoft
it seems to work as well.
radex
Per Apple's documentation, don't do this:"Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised."I don't know why it worked, but I would use the method Ben posted.
David Kanarek
I wonder the layers previously in the sublayer were actually released by using the method Ben posted. As David says, fast enumeration prohibits modification its collection.
KatokichiSoft
+2  A: 

The simplest way to remove all sublayers from a layer is to set the sublayer property to nil:

rootLayer.sublayers = nil;

Pascal Bourque
Does that automatically dealloc the layers within it?
Joe
As far as I can tell, yes it does (of course, it simply releases the sublayers, and they will only be deallocated if nothing else is retaining them).
Pascal Bourque