2016-03-30 64 views
4

我們需要將下面的代碼從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); 

斯威夫特版本至今:

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 
} 

回答

7

每文檔:

核心基礎類型自動導入爲全面斯威夫特類。無論在哪裏提供內存管理註釋,Swift都會自動管理Core Foundation對象的內存,包括您自己實例化的Core Foundation對象。

因此您可以省略調用。

+0

完美,只是想確認!謝謝! – Crashalot

1

沒有你不需要釋放核心基礎對象,因爲 蘋果說:

的核心基礎CFTypeRef類型完全重新映射到AnyObject 類型。

而且

核心基礎對象從註釋的API返回的是自動 內存管理斯威夫特,你不需要調用CFRetain, CFRelease,或CFAutorelease功能自己。

文件here

相關問題