ios - Swift 3 CGContext 内存泄漏

标签 ios swift memory-leaks cgimage

我正在使用 CGBitMapContext() 将颜色空间转换为 ARGB 并获取像素数据值,我为位图上下文分配空间并在完成后释放它,但我仍然在仪器中看到内存泄漏 I'我想我可能做错了什么,所以我们将不胜感激。

这是 ARGBBitmapContext 函数

func createARGBBitmapContext(width: Int, height: Int) -> CGContext {
    var bitmapByteCount = 0
    var bitmapBytesPerRow = 0

    //Get image width, height
    let pixelsWide = width
    let pixelsHigh = height

    bitmapBytesPerRow = Int(pixelsWide) * 4
    bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)


    let colorSpace = CGColorSpaceCreateDeviceRGB()
    // Here is the malloc call that Instruments complains of
    let bitmapData = malloc(bitmapByteCount)


    let context = CGContext(data: bitmapData, width: pixelsWide, height: pixelsHigh, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

    // Do I need to free something here first?
    return context!
}

这里是我使用上下文检索所有像素值作为 UInt8 列表的地方(以及内存泄漏的地方)

extension UIImage {

    func ARGBPixelValues() -> [UInt8] {
        let width = Int(self.size.width)
        let height = Int(self.size.height)
        var pixels = [UInt8](repeatElement(0, count: width * height * 3))

        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        let context = createARGBBitmapContext(inImage: self.cgImage!)
        context.clear(rect)
        context.draw(self.cgImage!, in: rect)

        var location = 0

        if let data = context.data {

            while location < (width * height) {
                let arrOffset = 3 * location
                let offset = 4 * (location)

                let R = data.load(fromByteOffset: offset + 1, as: UInt8.self)
                let G = data.load(fromByteOffset: offset + 2, as: UInt8.self)
                let B = data.load(fromByteOffset: offset + 3, as: UInt8.self)

                pixels[arrOffset]   = R
                pixels[arrOffset+1] = G
                pixels[arrOffset+2] = B

                location += 1
            }

            free(context.data) // Free the data consumed, perhaps this isn't right?
        }

        return pixels
    }
}

仪器报告 1.48MiB 的 malloc 错误,这适合我的图像大小 (540 x 720) 我释放了数据,但显然这是不正确的。

我应该提一下,我知道你可以将 nil 传递给 CGContext init(它会管理内存),但我更好奇为什么使用 malloc 会产生问题,我应该知道更多(我更熟悉 Obj -C).

最佳答案

因为 CoreGraphics 不是由 ARC 处理的(与所有其他 C 库一样),您需要使用自动释放来包装您的代码,即使在 Swift 中也是如此。特别是如果您不在主线程上(您不应该在主线程上,如果涉及 CoreGraphics....userInitiated 或更低版本是合适的)。

func myFunc() {  
    for _ in 0 ..< makeMoneyFast {
        autoreleasepool {
            // Create CGImageRef etc...
            // Do Stuff... whir... whiz... PROFIT!
        }
    }
}

对于那些关心的人,你的 Objective-C 也应该像这样包装:

BOOL result = NO;
NSMutableData* data = [[NSMutableData alloc] init];
@autoreleasepool {
    CGImageRef image = [self CGImageWithResolution:dpi
                                          hasAlpha:hasAlpha
                                     relativeScale:scale];

    NSAssert(image != nil, @"could not create image for TIFF export");

    if (image == nil)
        return nil;

    CGImageDestinationRef destRef = CGImageDestinationCreateWithData((CFMutableDataRef)data, kUTTypeTIFF, 1, NULL);
    CGImageDestinationAddImage(destRef, image, (CFDictionaryRef)options);
    result = CGImageDestinationFinalize(destRef);
    CFRelease(destRef);
}

if (result) {
    return [data copy];
} else {
    return nil;
}

参见 this answer了解详情。

关于ios - Swift 3 CGContext 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339784/

相关文章:

swift - 在 Swift 中汇总数组值时出错

c++ - SDL2 C++ - SDL_FreeSurface 不会从 RAM 中删除图像

ios - 执行从一个列表到另一个更新属性值的 Realm 迁移

ios - View 隐藏时如何禁用 UISlider 交互?

objective-c - 带透明度的 iPad 视频

c++ - valgrind 泄漏摘要中的上下文数量指的是什么?

python - Matplotlib 在 savefig 和 close() 后不释放内存

javascript - 获取 WKWebView 的内容高度不正确

swift - Info.plist 字典到枚举类型字典 :String

swift - URL 未传递给 appdelegate