Removing all CALayer's sublayers

Viewed 57736

I have trouble with deleting all of layer's sublayers. I currently do this manually, but that brings unnecessary 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?

Edit:

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

15 Answers

The following should work:

for (CALayer *layer in [[rootLayer.sublayers copy] autorelease]) {
    [layer removeFromSuperlayer];
}
[rootLayer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];

You could simply provide an identifier for the CAlayer you have added and remove it by searching for it. Like so

 let spinLayer = CAShapeLayer()
 spinLayer.path = UIBezierPath()
 spinLayer.name = "spinLayer"


  func removeAnimation() {
     for layer in progressView.layer.sublayers ?? [CALayer]()
         where layer.name == "spinLayer" {
           layer.removeFromSuperlayer()
       }
   }

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.

Related