我有一个程序,我在其中设置一个在后台线程上运行的完成块。在块中我设置了一个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可能失败的原因?
由于 乔
答案 0 :(得分:3)
cgFullImage
。 CGImage Core Foundation对象已取消分配,您正在使用已释放的对象。
核心基础对象指针类型(如CGImageRef
)不受ARC管理。您应该使用__attribute__((NSObject))
注释实例变量,或者将实例变量的类型更改为类似id
的Objective-C对象指针类型。