A Layer with a Delegate

This app draws the same animation as the previous example, but it redraws only the parts of the picture that have changed.

Until now, a delegate has always had to adopt a protocol, named in <angle brackets>. But the protocol adopted by our class Delegate is merely an informal protocol. There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy. See Using a Delegate to Provide Content.

Like the drawRect: method of class UIView, the drawLayer:inContext: should never be called explicitly. We trigger a call to drawRect: by calling the setNeedsDisplay method of class UIView; we trigger a call to drawLayer:inContext: by calling the setNeedsDisplay method of class CALayer.

drawRect: is called before drawLayer:inContext:. The two transformations that drawRect: applied to c (CGContextTranslateCTM and CGContextScaleCTM are still in force when the c is passed to drawLayer:inContext:. It’s the same c. I turned the θ instance variable of class View into a property for the convenience of class Delegate.

Source code in Pythagoras.zip

  1. main.m
  2. Class PythagorasAppDelegate
  3. Class View
  4. Class Delegate

Create the project

Create the new class Delegate.
File → New File… → Objective-C class Subclass of: NSObject

Project → Edit Active Target "Pythagoras" → General → Linked Libraries
Press the plus sign and add QuartzCore.framework.