在 VideoToolbox 中将 NSDictionary 转换为 CFDictionary



两者有什么区别

const void *keys[] = { kCVPixelBufferPixelFormatTypeKey };
OSStatus pixelFormatType = kCVPixelFormatType_32BGRA;
CFNumberRef pixelFormatTypeRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pixelFormatType);
const void *values[] = { pixelFormatTypeRef };
CFDictionaryRef destinationImageBufferAttrs = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);

CFDictionaryRef destinationImageBufferAttrs = (__bridge CFDictionaryRef)(@{(NSString*)kCVPixelBufferPixelFormatTypeKey:@(kCVPixelFormatType_32BGRA)});

如果我使用第二个,我会收到一个EXC_BAD_ACCESS错误。为什么?

在第一个代码示例中,存储到destinationImageBufferAttrs中的引用是拥有的,以后必须使用CFRelease释放(或传输到 ARC 控件(。

在第二个代码示例中,存储在destinationImageBufferAttrs中的引用受 ARC 控制,ARC 可以在分配后立即释放它,因为不再有 ARC 拥有的引用。

__bridge更改为__bridge_retained要将所有权从 ARC 转移到您自己的代码,您将负责为对象调用CFRelease

事实证明,当我想再次访问时,@{}文字在放入CFDictionaryRef后没有保留。所以下面的代码将代替:

NSDictionary *dic = @{(NSString*)kCVPixelBufferPixelFormatTypeKey:@(kCVPixelFormatType_32BGRA)}; // "dic" reference will retain the nsdic created with @ literal
CFDictionaryRef destinationImageBufferAttrs = (__bridge CFDictionaryRef)dic;

最新更新