Swift 4 CGContext绘制内存泄漏

时间:2018-07-02 15:45:41

标签: objective-c swift core-graphics

我有这段代码可以将UIImage转换为[UInt8](像素)

extension UIImage {
func pixelData() -> [UInt8]? {
    let size = self.size
    let dataSize = size.width * size.height * 4
    var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    var context = CGContext(data: &pixelData,
                            width: Int(size.width),
                            height: Int(size.height),
                            bitsPerComponent: 8,
                            bytesPerRow: 4 * Int(size.width),
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
    guard let cgImage = self.cgImage else { return nil }
    context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

    return pixelData
}
}

该函数被调用了很多次,通过调试,我注意到draw调用分配了+ 1MB(图像大小),该函数在函数结束后并未释放。

在内存调试信息中,以下是大多数内存的负责调用者:

Responsible Library: CoreGraphics

Responsible Caller: CGDataProviderCreateWithCopyOfData

有人可以帮忙解决此内存泄漏吗?

0 个答案:

没有答案