Search code examples
iphoneiosuiviewcore-animationcalayer

On iOS, if a subclass of CALayer is used with an empty display method, then app seems to go into infinite loop?


If a Single View app is created, with a FooView that subclasses UIView, and do a

NSLog(@"hello");

in drawRect, then it is printed.

And if I create a subclass of CALayer called CoolLayer, and add this method to FooView.m:

+(Class) layerClass {
    return [CoolLayer class];
}

and at the end of FooView.m's drawRect, do a

NSLog(@"layer's class is %@", self.layer.class);

then CoolLayer is printed. So now the view's underlaying layer is CoolLayer.

But when the following is added to CoolLayer.m:

-(void) display {

}

which is the method that is automatically called to redraw the layer (similar to drawRect), then no NSLog whatsoever was printed. It might be that the app went into an infinite loop. (even my touchesBegan that prints out NSLog messages is not printing). If a breakpoint is set at display, it will stop there once but when I continue the program, it will never arrive at display again. What is wrong with this and how can it be fixed?


Solution

  • The layer's display method will not be called again unless the layer is dirty, i.e. set to need a redisplay. This is usually a good thing, and is why you don't see the method being called more than once.

    Also, the normal implementation of display will call the drawInContext: method. Since you override this in your subclass, the drawRect: method of the view is never called. You need to either replicate the standard behavior of CALayer, or call the superclass' display method in your own implementation.