【问题标题】:Issues with threading, blocks, CGImageRef and scope线程、块、CGImageRef 和范围的问题
【发布时间】:2013-06-25 23:29:53
【问题描述】:

我有一个程序,我在其中设置了一个在后台线程上运行的完成块。在块内,我设置了一个 CGImageRef,然后在主线程上设置我的图层内容。问题是,有时应用程序在主线程部分崩溃。

这是完成块,在下面的代码中,fullImage 和 cfFullImage 都在我的 .h 中声明

requestCompleteBlock completionBlock = ^(id data)
{
    // Seems I need to hold onto the data for use later
    fullImage = (NSImage*)data;
    NSRect fullSizeRect = NSMakeRect(0, 0, self.frame.size.width, self.frame.size.height);

    // Calling setContents with an NSImage is expensive because the image has to
    // be pushed to the GPU first. So, pre-emptively push it to the GPU by getting
    // a CGImage instead.
    cgFullImage = [fullImage CGImageForProposedRect:&fullSizeRect context:nil hints:NULL];

    // Rendering needs to happen on the main thread or else crashes will occur
    [self performSelectorOnMainThread:@selector(displayFullSize) withObject:nil waitUntilDone:NO];
};

我的完成块的最后一行是调用 displayFullSize。该功能如下。

- (void)displayFullSize
{
    [self setContents:(__bridge id)(cgFullImage)];
}

您是否看到或知道 setContents 可能失败的任何原因?

谢谢 乔

【问题讨论】:

    标签: objective-c objective-c-blocks performselector cgimageref background-thread


    【解决方案1】:

    cgFullImage 不保留。 CGImage Core Foundation 对象已解除分配,您正在使用已解除分配的对象。

    CGImageRef 这样的Core Foundation 对象指针类型不受ARC 管理。您应该使用__attribute__((NSObject)) 注释实例变量,或者将实例变量的类型更改为像id 这样的Objective-C 对象指针类型。

    【讨论】:

    • 感谢您的回复。添加一个 typedef 和一个类级别的属性就可以了。 typedef __attribute__((NSObject)) CGImageRef RenderedImageRef; @property (strong, nonatomic) RenderedImageRef renderedImage;快乐编码,乔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多