目标c renderInContext在后台线程崩溃 [英] objective c renderInContext crash on background thread

查看:1384
本文介绍了目标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((ori​​entation == UIInterfaceOrientationLandscapeLeft)||(orientation == UIInterfaceOrientationLandscapeRight)||(orientation == UIInterfaceOrientationPortraitUpsideDown)){
img = [self rotatedImage:img];
}
return img;
}

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


  1. 这个崩溃的原因是什么?

  2. 一个苹果建议,因为有renderInContext也使用)。没有呈现的内容...?



解决方案

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


I have an app in which the screen continuously is capturing in background thread. Here is the code

- (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;
}

It works good for capturing once or twice. But after a while the app crashes always on the same line [[keyWindow layer] renderInContext:context]; and it gives EXC_BAD_ACCESS (code=1, address=0x8) message. I searched everywhere and nothing useful. Found only that renderInContext has memory leak issue when it works in background thread. But as you understand that doesn't solve my issue :) . So have 3 questions :-

  1. What is the reason of this crash (problem)?

  2. What can I do with this?

  3. Is there any other way to capture screen (beside the one that Apple suggests, because there renderInContext is also used). Something without rendering...?

解决方案

-renderInContext: is not thread-safe and you can't call it from a background thread. You'll have to do the drawing on the main thread.

这篇关于目标c renderInContext在后台线程崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆