0

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

我相信 CFDictionary 的 CFArray 的自定义回调会有所帮助,但是我正在寻找一个插入式、经过良好测试的解决方案

4

1 回答 1

2

回调和集合创建很简单:

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_ts 进出集合。您不能简单地将类型变量强制dispatch_object_t转换为 a 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;
}
于 2013-01-05T10:20:46.180 回答