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 –