我是否需要在ARC下调用dispatch_release?

时间:2013-10-18 16:09:29

标签: ios objective-c automatic-ref-counting grand-central-dispatch

(但这个问题完全不同)

这个非ARC代码示例设置一个基于GCD的计时器,它为dispatch_source_t对象调用dispatch_release:

    __block BOOL done = NO;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    if (timer) {
        uint64_t milliseconds = 100ull;
        uint64_t interval = milliseconds * NSEC_PER_MSEC;
        uint64_t leeway = 10ull * NSEC_PER_MSEC;
        __block typeof(self) _self = self;

        dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
        dispatch_source_set_event_handler(timer, ^{
            //[_progressBar setProgress:exportSession.progress animated:YES];
            if (done) {
                dispatch_source_cancel(timer);
                dispatch_release(timer);
                _self.exportingMovieLabel.hidden = YES;
                _self.exportingProgress.hidden = YES;
            }
        });

        dispatch_resume(timer);
    }

我了解到您不必在ARC下发布队列对象。但其他GCD对象如调度源?

2 个答案:

答案 0 :(得分:8)

否,前提是您的部署目标是iOS 6.0或Mac OS X 10.8或更高版本,如here所述。

所有GCD对象都由ARC管理,因此您无需明确管理其内存。 dispatch_queue_t的真实情况也适用于所有其他GCD对象。

<os/object.h>的定义正上方OS_OBJECT_HAVE_OBJC_SUPPORT中记录了这一点。

  

默认情况下,在使用Objective-C编译器构建时,将诸如GCD和XPC对象的libSystem对象声明为Objective-C类型。这允许他们参与ARC,通过Blocks运行时进行RR管理,并通过静态分析器进行泄漏检查,并使它们能够添加到Cocoa集合中。

您也可以使用-DOS_OBJECT_USE_OBJC=0编译器标志选择退出此行为。

答案 1 :(得分:1)

这是要添加到代码中的编译器指令。

// If GCD objects are treated as Objective C object then we do not need to call dispatch_release on those GCD object.
// Checking if OS_OBJECT_HAVE_OBJC_SUPPORT == 0 ensures we are only releasing GCD objects when they are NOT being treated as Objective C objects.
#if OS_OBJECT_HAVE_OBJC_SUPPORT == 0
    dispatch_release(timer);
#endif