gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:36:49 24 4
gpt4 key购买 nike

我正在编写一个感知匹配程序(以实际学习 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
}
}

当我在“主”函数中声明位图实例时,一切正常。但是,当我在函数中使用它时,关联的内存不会在函数终止时被释放。当我转换图像时,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 张图像后我用完了内存。

最佳答案

the associated memory does not get released when the function terminates

这对于自动释放的内存来说是完全正常的。您不应期望在函数终止时回收内存。你应该期望它在自动释放池耗尽时被回收。这是在每个事件循环结束时自动完成的,例如在 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)
// ...
}
}
}

关于swift - 在函数中使用时未释放类内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36292853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com