negersiu negersiu - 3 months ago 23
Objective-C Question

Stop drawing of CATiledLayer

Is is possible to stop

to draw (drawLayer:inContext)?
It draws asynchronously and when i try to release CGPDFDocumentRef, which is used by
, the app crashes (EXC_BAD_ACCESS).

That's my view:

@implementation TiledPDFView

- (id)initWithFrame:(CGRect)frame andScale:(CGFloat)scale{
if ((self = [super initWithFrame:frame])) {

CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
tiledLayer.levelsOfDetail = 4;
tiledLayer.levelsOfDetailBias = 4;
tiledLayer.tileSize = CGSizeMake(512.0, 512.0);
myScale = scale;
return self;

// Set the layer's class to be CATiledLayer.
+ (Class)layerClass {
return [CATiledLayer class];

- (void)stopDrawing{
CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
[tiledLayer removeFromSuperlayer];
tiledLayer.delegate = nil;
// Set the CGPDFPageRef for the view.
- (void)setPage:(CGPDFPageRef)newPage
self->pdfPage = CGPDFPageRetain(newPage);

//self->pdfPage = newPage;


// Draw the CGPDFPageRef into the layer at the correct scale.
-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context

// First fill the background with white.
CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);

// Flip the context so that the PDF page is rendered
// right side up.
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// Scale the context so that the PDF page is rendered
// at the correct size for the zoom level.
CGContextScaleCTM(context, myScale,myScale);
CGContextDrawPDFPage(context, pdfPage);


// Clean up.
- (void)dealloc {

[super dealloc];

And this is where i try to stop and release PDF in view controller:
is instance of

-(void) stopDwaring {
[v stopDrawing];
[v removeFromSuperview];
[v release];
[self.view removeFromSuperview];
self.view = nil;



this post helped me solving my own trouble with CATiledLayer. I used TiledPDFview.m from Apple's documentation as example. Since I need to redraw the entire view and all tiles at some point, I use a CATiledLayer as property. When exiting and deallocating the viewcontroller, it crashed with [CATiledLayer retain]: Message sent to deallocated instance. Here is my dealloc method of the view controller:

- (void)dealloc {
    [self.tiledLayer removeFromSuperlayer];

    // note: releasing the layer still crashes- 
    // I guess removeFromSuperlayer releases it already, 
    // but couldn't find documentation so far.
    // So that's why it's commented out:
    // [self.tiledLayer release], self.tiledLayer=nil;

    //release the other viewcontroller stuff... 
    [super dealloc];

That works for me. Hope it helps someone.