CGContextDrawLayerAtPoint Problems in Mac OS Sonoma

My app stopped working in Mac OS Sonoma 14.0 and I quickly isolated the problem to CGContextDrawLayerAtPoint. Two issues, first of all about 1/2 the time there was no data copied (the updated CGLayer did not show up in the window). Then the app would crash iin libswiftCore.dylib after about 5 updates with a very unusual message: "Fatal error: Duplicate keys of type 'DisplayList' were found in a Dictionary. This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion". This behavior showed up in builds built with XCode 13 on a Mac OS Montery platform, as well as XCode 15 on Mac OS Ventura when the app was run on Sonoma.

My app uses a very traditional method to create an off-screen graphics context in drawRect:

- (void)drawRect:(NSRect)dirtyRect {
   // Obtain context from the current NSGraphicsContext ...
   viewNSContext = [NSGraphicsContext currentContext];
   viewCGContext = (CGContextRef)[viewNSContext graphicsPort];
   drawingLayer  = CGLayerCreateWithContext(viewCGContext, size, NULL);

So the exact details of the off-screen drawing area were based upon the characteristics of the window being drawn to.

Fortunately the work-around was very easy. By creating a custom CGBitmapContext everything was resolved. My drawing requirements are very basic, so a simple 32-bit RGB off-screen context was adequate.

colorSpaceRef    = CGColorSpaceCreateDeviceRGB();
bitMapContextRef = CGBitmapContextCreate(NULL, (int) rintf(size.width), (int) rintf(size.height), 8, 0, colorSpaceRef, kCGImageAlphaNoneSkipLast);
drawingLayer     = CGLayerCreateWithContext(bitMapContextRef, size, NULL);

Once I changed to a bitmap offscreen context, problem resolved.

In my case I verified that the portion of the window that was updated with the CGContextDrawLayerAtPoint was indeed restricted to the dirty part of the view rectangle, at least in Sonoma 14.5.

Hope this helps someone else searching for the issue, as I found nothing in the Forums or online.

Thanks for documenting your workaround. Did you ever report this using Feedback Assistant?

CGContextDrawLayerAtPoint Problems in Mac OS Sonoma
 
 
Q