如何解决SpriteKit SKTexture的CGImage "Context leak"?

How to solve SpriteKit SKTexture's CGImage "Context leak"?

Xcode 11-12,MacOS Catalina,Swift 5 个项目...

此代码产生“检测到上下文泄漏,msgtracer 返回 -1”错误:

import Foundation
import SpriteKit
import GameKit

func getTextureImage(_ index: Int, isSky: Bool = true) -> CGImage {
    
    let perlinSource = GKPerlinNoiseSource(
        frequency: 1,
        octaveCount: 7,
        persistence: 0.5,
        lacunarity: 2.0,
        seed: 123
    )
    
    let noise = GKNoise(perlinSource)
    
    noise.gradientColors = [
        -1.0: NSColor(red: 0.0, green: 0.15, blue: 0.85, alpha: 1.0),
        1.0 : NSColor(red: 1, green: 1, blue: 1, alpha: 1.0),
    ]
    
    noise.move(by: vector_double3(Double(index), 0, 0))
    
    let noiseMap = GKNoiseMap(noise,
                              size: SIMD2(repeating: 1),
                              origin: SIMD2(repeating: 0.0),
                              sampleCount: SIMD2(repeating: 16),
                              seamless: false)
    
    let t = SKTexture(noiseMap: noiseMap)
    let i = t.cgImage()
    
    return i
}


for x in 0...128 {
    
    let texture = getTextureImage(x)
    
}

如何解决与 .cgImage() 方法调用一致的错误? 我需要来自彩色 GKNoiseMap 的 CGImage 数据,然后我将使用它与 MetalKit 一起将数据加载到 MTLTexture

MTKTextureLoader.newTexture(cgImage: texture, options: textureLoaderOptions)

是啊,我当然试过了

autoreleasepool {
    let t = getTextureImage(x)
}

并解决了问题 :) 所以,你必须在 Swift API

中将 autoreleasepool 与 NSImage 和 CGI​​mage 一起使用