O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required