目标c renderInContext在后台线程上崩溃

我有一个应用程序,其中屏幕不断在后台线程捕获。 这是代码

- (UIImage *) captureScreen { UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; CGRect rect = [keyWindow bounds]; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [[keyWindow layer] renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIDeviceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight) || (orientation==UIInterfaceOrientationPortraitUpsideDown)) { img=[self rotatedImage:img]; } return img; } 

它适用于捕捉一次或两次。 但一段时间后,应用程序总是崩溃在同一行[[keyWindow layer] renderInContext:context]; 并给出EXC_BAD_ACCESS (code=1, address=0x8)消息。 我到处search,没有什么用处。 只发现renderInContext在后台线程中工作时存在内存泄漏问题。 但是,正如你所理解的,并不能解决我的问题:)。 所以有3个问题:

  1. 这个崩溃(问题)的原因是什么?

  2. 我能用这个做什么?

  3. 有没有其他的方法来捕捉屏幕(旁边的苹果build议,因为renderInContext也被使用)。 没有渲染的东西…?

-renderInContext:不是线程安全的,你不能从后台线程调用它。 你将不得不在主线上进行绘图。

我没有做任何事情,只是在主线程上执行这个方法。 我重新组织了我的线程pipe理,可以为我取得好成绩:

[self performSelectorOnMainThread:@selector(captureScreenOnMainThread) withObject:nil waitUntilDone: YES]; 最后一个参数在某些情况下可以设置为no …

感谢所有的回应。