【问题标题】:Make CVDisplayLink + Automatic Reference Counting play well together让 CVDisplayLink + Automatic Reference Counting 配合得很好
【发布时间】:2012-01-12 13:35:42
【问题描述】:

我最近从使用 NSTimer 切换到 CVDisplayLink 来重绘我的 OpenGL 动画,但在打开 ARC 时我遇到了一点问题:

/*
 * This is the renderer output callback function.
 */
static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext)
{
  // now is the time to render the scene
  [((__bridge BDOpenGLView*)displayLinkContext) setNeedsDisplay:YES];
  // always succeeds, because we don't actually do anything here anyway
  return kCVReturnSuccess;
}

显示链接回调函数必须用C编写,作为参数使用

// set the renderer output callback function
CVDisplayLinkSetOutputCallback(displayLink, &displayLinkCallback, (__bridge void*)self);

所以我不能在回调中使用self,但是使用((__bridge BDOpenGLView*) displayLinkContext) 会产生内存泄漏:

objc[29390]: Object 0x1001b01f0 of class NSConcreteMapTable autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug

我读到,我必须自己设置一个NSAutoreleasePool,但我不能在 ARC 开启的情况下。

我错过了什么吗?

【问题讨论】:

    标签: objective-c cocoa core-animation automatic-ref-counting


    【解决方案1】:

    用新的@autoreleasepool 块包围代码:

    @autoreleasepool {
      // your c callback code here
    }
    

    【讨论】:

    • 一个月前我将一些 GC 代码迁移到 ARC 时遇到了同样的问题。我已经习惯了阻塞和 they don't need explicit autorelease pools 的事实,以至于我忘记了为 CVDisplayLink 使用其回调的后台线程创建一个。
    猜你喜欢
    • 2010-09-11
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2017-05-27
    • 2014-04-07
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多