Removing a CALayer at index 0

Funfunfun...

There are two layer properties you can use (in either case you have to iterate over the layers):

  • CALayer.name "is used by some layout managers to identify a layer". Set it to something reasonably guaranteed to be unique (e.g. "MyClassName.gradient").
  • CALayer.style is a dictionary. You can use keys which aren't used by CoreAnimation (e.g. NSMutableDictionary * d = [NSMutableDictionary dictionaryWithDictionary:layer.style]; [d setValue:[NSNumber numberWithBool:YES] forKey:@"MyClassName.gradient"]; layer.style = d;). This might be useful to associate arbitrary data with a view (such as the index path of the cell containing a text field...).

(I'm assuming that [NSDictionary dictionaryWithDictionary:nil] returns the empty dictionary instead of returning nil or throwing an exception. The corresponding thing is true for [NSArray arrayWithArray:nil].)

However, the extra code complexity, performance penalty, and chance of getting it wrong probably outweigh the small decrease in memory usage. 4 bytes per view is not that much if you have a handful of views (and even if you have loads, 4 bytes is the memory used by a single pixel!).


Swift has some really simple solutions for this:

// SWIFT 4 update
func removeSublayer(_ view: UIView, layerIndex index: Int) {
    guard let sublayers = view.layer.sublayers else {
        print("The view does not have any sublayers.")
        return
    }
    if sublayers.count > index {
        view.layer.sublayers!.remove(at: index)
    } else {
        print("There are not enough sublayers to remove that index.")
    }
}
// Call like so
removeSublayer(view, layerIndex: 0)

Just remember, the sublayers are treated as an array, so if you have a count of 2, then 2 == 1 in the index, hence removeAtIndex(1).

There are a whole heap of options available for editing sublayers. Simply stop typing after sublayers!. and check them out.


You can do it the way you described but it isn't so reliable. The problem is that if you do anything with the sublayers in between the addition and removal, the index of the sublayer can change and you end up removing something you didn't want to.

The best thing is to keep a reference to that layer and later when you want to remove it just call [theLayer removeFromSuperlayer]

Hope it helps