How to avoid strange memory leak when loading local JPG file on MacOS

In my app, I need to show user's local file whose location is stored in a ObservableObject called ImageModel. Values of ImageModel will be changed in background and affect the interface.

Strange memory leak happens when loading local JPG file in background (window not being the key or main window). I call it strange because when the window becomes key or main window, the memory will be correctly released, but the memory consumed endlessly increases when window is in background.

According to Instrument, memory leak is caused by AppleJPEGReadPlugin::copyIOSurfaceCallback.
XCode 11.6 on MacOS 10.15.6

Is this a bug and is there a way to avoid this?

I made my code as simple as possible.

ImageView.swift
Code Block swift
import SwiftUI
struct ImageView: View {
  @EnvironmentObject var image: ImageModel
  var body: some View { image.getImage() }
}
class ImageModel: ObservableObject {
  @Published var toggle: Bool = true
  func getImage() -> Image {
    return Image(nsImage: NSImage(byReferencing: URL(fileURLWithPath: "/Users/geeeeoff/Downloads/demo.jpeg")))
  }
}


AppDelegate.swift
Code Block swift
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
  var window: NSWindow!
  var image = ImageModel()
  func applicationDidFinishLaunching(_ aNotification: Notification) {
    window = NSWindow(
      contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
      styleMask: [.titled, .closable],
      backing: .buffered, defer: false
    )
    let contentView = ImageView().environmentObject(image)
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.image.toggle.toggle() }.fire()
    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
  }
}

Replies

Any updates on this? I'm still facing the same issue.
I'm experiencing the same issue and would love to know if this has been resolve, acknowledged or if I am doing something wrong.