OC 转 CF
NSArray *anArray = @[@1,@2,@3,@4];
CFArrayRef aCFArray = (__bridge CFArrayRef)anArray;
NSLog(@"Size of array = %ld",CFArrayGetCount(aCFArray));
__bridge
的意思:ARC 仍具备这个 OC 对象的保留权。
NSArray *anArray = @[@1,@2,@3,@4];
CFArrayRef aCFArray = (__bridge CFArrayRef)anArray;
NSLog(@"Size of array = %ld",CFArrayGetCount(aCFArray));
CFRelease(aCFArray);
__bridge_retained
: ARC 交出对象的所有权,使用完之后需要调用CFRelease()。
CF 转 OC
使用 __bridge__transfer
在CoreFoundation 创建字典
const void* EOCRetainCallback(CFAllocatorRef allocator, const void *value)
{
return CFRetain(value);
}
void EOCReleaseCallback(CFAllocatorRef allocator, const void *value)
{
CFRelease(value);
}
CFDictionaryKeyCallBacks keyCallbacks = {
0,
EOCRetainCallback,
EOCReleaseCallback,
NULL,
CFEqual,
CFHash
};
CFDictionaryValueCallBacks valueCallbacks = {
0,
EOCRetainCallback,
EOCReleaseCallback,
NULL,
CFEqual
};
CFMutableDictionaryRef aCFDictionary = CFDictionaryCreateMutable(NULL, 10, &keyCallbacks, &valueCallbacks);
NSMutableDictionary *anNSDictionary = (__bridge_transfer NSMutableDictionary*)aCFDictionary;
Foundation层的字典,其键的内存管理语义是“拷贝”,值的语义是保留。
如果字典中加入新的键值,就会调用retain函数。
直接在CF层创建字典,就能修改键值的内存管理语义。