【问题标题】:Memory leaks when generating dispatch source timer events生成调度源计时器事件时发生内存泄漏
【发布时间】:2011-04-10 17:50:25
【问题描述】:

我们使用调度队列来生成计时器事件。以下是执行该任务的代码:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (!timer) 返回自我; dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 5 * NSEC_PER_SEC); dispatch_source_set_event_handler(定时器, ^{ //一些工作… });

这很好用,除了当我们运行分析器时,我们看到这些方法有很多内存泄漏:

  • dispatch_source_create
  • dispatch_source_set_timer
  • dispatch_source_set_event_handler

我们已确保使用 dispatch_release() 方法释放计时器。

如果我们在上面的代码中犯了任何错误,有人可以告诉我们吗?此外,如果您能指出任何计时器事件生成的示例,那将会很有帮助。

【问题讨论】:

    标签: iphone ios ipad memory-leaks grand-central-dispatch


    【解决方案1】:

    dispatch_source_set_timer(3) Mac OS X Manual Page

    所有计时器将无限重复,直到 dispatch_source_cancel() 被调用。

    如何为定时器调用 dispatch_source_cancel() 和 dispatch_release()?

    调度源定时器示例:

    dispatch_source_t timer = dispatch_source_create(
        DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
            dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    
    dispatch_source_set_timer(timer,
        dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC),
            DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"wakeup!");
    
        dispatch_source_cancel(timer);
    });
    
    dispatch_source_set_cancel_handler(timer, ^{
        NSLog(@"canceled");
    
        dispatch_release(timer);
    });
    
    dispatch_resume(timer);
    

    【讨论】:

    • 感谢您的回复。我将您的示例代码与我的进行了比较。它看起来几乎一样。我在 dealloc 中执行取消和释放,我可以看到它被调用了。对我来说,定时器事件被正确引发并且一切正常。问题是,我在运行分析器时看到内存泄漏。
    猜你喜欢
    • 2014-12-11
    • 2013-07-09
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2016-03-24
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多