gpt4 book ai didi

ios - 将 Objective-C 代码转换为 Swift : okay to omit release calls?

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:07 25 4
gpt4 key购买 nike

我们需要将下面的代码从 Objective-C 转换为 Swift。

问题:

有一些函数调用可以释放对象,例如,CGImageRelease(newImage)。假设 Swift 版本不需要模拟是安全的,因为所有内存管理都是自动的,还是您也需要在 Swift 中释放内存?

Objective-C 代码:

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef newImage = CGBitmapContextCreateImage(newContext); CGContextRelease(newContext);
CGColorSpaceRelease(colorSpace);
UIImage *image= [UIImage imageWithCGImage:newImage scale:1.0 orientation:orientation];
CGImageRelease(newImage);

到目前为止的 Swift 版本:

private func turnBufferToPNGImage(imageSampleBuffer: CMSampleBufferRef, scale: CGFloat) -> UIImage {
let imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer)

// Lock base address
CVPixelBufferLockBaseAddress(imageBuffer, 0)

// Set properties for CGBitmapContext
let pixelData = CVPixelBufferGetBaseAddress(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()

// Create CGBitmapContext
let newContext = CGBitmapContextCreate(pixelData, width, height, 8, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue)

// Create image from context
let rawImage = CGBitmapContextCreateImage(newContext)!
let newImage = UIImage(CGImage: rawImage, scale: scale, orientation: .Up)

// Unlock base address
CVPixelBufferUnlockBaseAddress(imageBuffer,0)

// Return image
return newImage
}

最佳答案

根据文档:

Core Foundation types are automatically imported as full-fledged Swift classes. Wherever memory management annotations have been provided, Swift automatically manages the memory of Core Foundation objects, including Core Foundation objects that you instantiate yourself

因此您可以省略调用。

关于ios - 将 Objective-C 代码转换为 Swift : okay to omit release calls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321839/

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