Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe way to render UIVIew to an image on background thread?

I'm creating small tile images to be stored on disk and displayed to the user. Here is my current process for doing this:

  1. Create a viewcontroller that represents the UI I want to show onscreen
  2. Get the view from the viewcontroller and render an image from it
  3. Save it to disk and display it onscreen later

I am crashing when I attempt to access the view of the viewcontroller. When I tried to research this online, I am getting conflicting results on whether it is safe to create the view in the background. I'm reading that the UIGraphicsGetCurrentContext call should be thread safe, but maybe not accessing the UIView on a background thread? I'm writing the app for iOS 4 and above. Here is the code I'm using (tile is the viewcontroller):

CGSize size = CGSizeMake(20.0f, 30.0f);
UIGraphicsBeginImageContext(size);
[tile.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();           
UIGraphicsEndImageContext();

The crash occurs when trying to access the .view property on the tile (EXC_BAD_ACCESS). The whole point is to render the view to an image in the background to prevent locking up the UI because there are a lot of tiles to process.

Is there a safe way to do this?

like image 768
Mark Struzinski Avatar asked Jun 14 '11 19:06

Mark Struzinski


1 Answers

I've never tried what you described, and I don't like being the bearer of bad news, but taken from Apple's documentation.

Note: For the most part, UIKit classes should be used only from an application’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application’s user interface in any way.

Of course, they conveniently say "For the most part", so that leaves some wiggle room.

like image 148
Pieter Avatar answered Oct 19 '22 15:10

Pieter