将 Objective-C 代码转换为 Swift:可以省略发布调用吗?

Converting Objective-C code to Swift: okay to omit release calls?

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

所以你可以省略电话。

否 你不需要释放 Core Foundation 对象,因为 苹果说:

The Core Foundation CFTypeRef type completely remaps to the AnyObject type.

Core Foundation objects returned from annotated APIs are automatically memory managed in Swift—you do not need to invoke the CFRetain, CFRelease, or CFAutorelease functions yourself.

文档here