在函数中使用时未释放类内存

时间:2016-03-29 18:57:06

标签: swift function class memory memory-leaks

我正在写一个感性匹配程序(实际上学习Swift)。我有以下挑战:

我有一个类将CGImage转换为位图,随后读取单个像素(参见How do I load and edit a bitmap file at the pixel level in Swift for iOS?

class Bitmap {       

let width: Int
let height: Int
let context: CGContextRef

init(img: CGImage) {

    // Set image width, height
    width = CGImageGetWidth(img)
    height = CGImageGetHeight(img)

    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and alpha.
    let bitmapBytesPerRow = width * 4
    // Use the generic RGB color space.
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)

    // Create the bitmap context. 
    context = CGBitmapContextCreate(nil, width, height, 8, bitmapBytesPerRow, colorSpace, bitmapInfo.rawValue)!

    // draw the image onto the context
    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    CGContextDrawImage(context, rect, img)

}

deinit {
}


func color_at(x: Int, y: Int)->(Int, Int, Int, Int) {

    assert(0<=x && x<width)
    assert(0<=y && y<height)

    let uncasted_data = CGBitmapContextGetData(context)
    let data = UnsafePointer<UInt8>(uncasted_data)

    let offset = 4 * (y * width + x)

    let alpha = data[offset]
    let red = data[offset+1]
    let green = data[offset+2]
    let blue = data[offset+3]

    let color = (Int(red), Int(green), Int(blue), Int(alpha))
    return color
    }
}

当我在我的&#34; main&#34;中声明Bitmap的实例时功能,一切正常。但是,当我在函数中使用它时,当函数终止时,相关的内存不会被释放。当我转换图像时,RAM不断增加,我的iMac崩溃了。有什么想法为什么记忆不相关?

举例说明:

func fingerprintImage(fileName: String) -> Int {

    //
    // Load the image and convert to bitmap
    //
    let url = NSURL(fileURLWithPath: fileName)
    let image:CIImage=CIImage(contentsOfURL: url)!
    let bitmap = Bitmap(img: convertCIImageToCGImage(image)) 
    return 0
}

let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath("<... PATH TO DIRECTORY WITH IMAGES, EG CANON CR2>")!
while let element = enumerator.nextObject() as? String {
    if element.hasSuffix("CR2") { 
        var fp2 = fingerprintImage(""<... PATH TO DIRECTORY WITH IMAGES, EG CANON CR2>"/"+element)
    }
}

我原本预计当fingerprintImage终止时会释放位图但事实并非如此 - 大约50张图像后我的内存耗尽。

1 个答案:

答案 0 :(得分:2)

  

当函数终止时,相关内存不会被释放

对于自动释放的内存来说,这是完全正常的。当函数终止时,你不应该期望回收内存。当自动释放池耗尽时,您应该期望它被回收。这是在每个事件循环结束时自动完成的,例如在iOS上的绘图周期之间,但是如果你继续在循环中调用fingerprintImage,或者以自动释放池没有的方式运行它为你自动排水,你需要自己动手。

在您的示例(循环)中,您通常会执行以下操作:

while let element = enumerator.nextObject() as? String {
    autoreleasepool {
        if element.hasSuffix("CR2") { 
            var fp2 = fingerprintImage(""<... PATH TO DIRECTORY WITH IMAGES, EG CANON CR2>"/"+element)
            // ...
        }
    }
}