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

Gar*_*nik 4 cocoa-touch screen-capture cgcontext mainwindow ios

我有一个应用程序,其中屏幕连续捕获后台线程.这是代码

- (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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

  2. 我该怎么办?

  3. 有没有其他方法来捕获屏幕(在Apple建议的旁边,因为还使用了renderInContext).没有渲染的东西......?

Fab*_*ser 8

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