Layers and Key–Value Coding

Earlier, I showed that aspects of a layer’s transform were accessible through key–value coding. This feature stems from the fact that CALayer is KVC compliant for the @"transform" key. The same is true of all of a layer’s properties; they are all accessible through KVC by way of keys with the same name as the property. Thus, to apply the mask in the previous example, we could have said:

[arrow setValue: mask forKey: @"mask"];

But a layer goes further than this. You can treat a CALayer as a kind of NSDictionary, and get and set the value for any key. This is tremendously useful, because it means you can attach arbitrary information to an individual layer instance and retrieve it later. For example, earlier I mentioned that to apply manual layout to a layer’s sublayers, you will need a way of identifying those sublayers. This feature could provide a way of doing that. It will also come in handy in connection with animation.

Also, CALayer has a defaultValueForKey: class method; to implement it, you’ll need to subclass and override. In the case of keys whose value you want to provide a default for, return that value; otherwise, return the value that comes from calling super. Thus, even if a value for a particular key has never been explicitly provided, it can have a non-nil value.

The truth is that this feature, though delightful (and I often wish that all classes behaved like this), is not put there for your convenience and enjoyment. It’s there to serve as ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.