0

我有一个程序,我在后台线程上运行一个完成块。在块内部,我设置了一个CGImageRef,然后在主线程中设置了我的图层内容。问题是,有时应用程序在主线程部分崩溃。线程,块,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失败的原因?

感谢 乔

回答

3

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

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

+0

感谢您的回应。 添加一个typedef和一个类级别的属性做了诀窍。 'typedef __attribute __((NSObject))CGImageRef RenderedImageRef; @property(strong,nonatomic)RenderedImageRef renderedImage;' 快乐编码, Joe –