gpt4 book ai didi

cocoa - 如何将 GCD 对象放入 CF 集合(CFArray、CFDictionary)中?

转载 作者:行者123 更新时间:2023-12-03 17:41:11 27 4
gpt4 key购买 nike

部署目标是10.6,因此需要手动内存管理。该集合应该负责保留/释放 GCD 对象。

我相信 CFDictionary 的 CFArray 的自定义回调会有所帮助,但是我正在寻找一个简单的、经过充分测试的解决方案

最佳答案

回调和集合创建非常简单:

static const void * dispatchObjectRetainCallBack(CFAllocatorRef allocator, const void *value)
{
if (value) {
dispatch_retain(value);
}
return value;
}

static void dispatchObjectReleaseCallBack(CFAllocatorRef allocator, const void *value)
{
if (value) {
dispatch_release(value);
}
}

CFMutableArrayRef CreateDispatchHoldingArray()
{
CFArrayCallBacks callBacks = {
0,
dispatchObjectRetainCallBack,
dispatchObjectReleaseCallBack,
NULL,
NULL
};
return CFArrayCreateMutable(kCFAllocatorDefault, 0, &callBacks);
}

CFMutableDictionaryRef CreateDispatchHoldingDictionary()
{
CFDictionaryValueCallBacks valueCallBacks = {
0,
dispatchObjectRetainCallBack,
dispatchObjectReleaseCallBack,
NULL,
NULL
};
return CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &valueCallBacks);
}

稍微棘手的部分是将 dispatch_object_t 放入和取出集合。您不能简单地将 dispatch_object_t 类型的变量转换为 void *,因为 dispatch_object_t 是联合的 typedef。编译器报错:

Operand of type 'dispatch_object_t' where arithmetic or pointer type is required

您必须遍历 dispatch_object_t 内的联合类型之一,如下所示:

void AddDispatchObjectToArray(CFMutableArrayRef array, dispatch_object_t obj)
{
void* voidPtrObj = obj._do;
CFArrayAppendValue(array, voidPtrObj);
}

dispatch_object_t GetDispatchObjectAtIndex(CFMutableArrayRef array, CFIndex index)
{
dispatch_object_t result;
result._do = (struct dispatch_object_s *)CFArrayGetValueAtIndex(array, index);
return result;
}

关于cocoa - 如何将 GCD 对象放入 CF 集合(CFArray、CFDictionary)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14147565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com