vendredi 31 juillet 2015

Load an image from an asset catalog off the main thread?

I'm trying to load an image from an asset catalog into a UIImage off of the main thread, but can't seem to find any way to do it. If the image was not in an asset catalog I would use pathForResource and imageWithContentsOfFile:

NSString *path = [[NSBundle mainBundle] pathForResource:icon ofType:nil];
if(path) {
  image = [UIImage imageWithContentsOfFile:path];
}

But pathForResource: does not work for images in asset catalogs. Is there any way to do this without having to go to the main thread to load the image? Im guessing the answer is no.

What won't work:

  • Manually creating the path for the image based on the main bundle path. I have images in multiple asset catalogs, and asset catalogs can be compiled in a binary form.
  • [UIImage imageNamed:] is not thread safe, and can not be used off the main thread. The docs have said it's not thread safe for at least the last several major releases of iOS, and starting in iOS 8 it really does crash when used off the main thread.

What i'm doing now:

dispatch_sync(dispatch_get_main_queue(), ^{
  image = [UIImage imageNamed:icon];
});

Aucun commentaire:

Enregistrer un commentaire