ios – 将Objective-C代码转换为Swift:可以省略释放调用吗?

我们需要将以下代码从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,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

所以你可以省略这些电话.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...