Monday, May 21, 2012

Load UIImage from file using grand central dispatch

I'm trying to load images in the background using gcd. My first attempt didn't work:



dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// create UI Image, add to subview
});
});


commenting out the background queue code and leaving just the main queue dispatch block didn't work:



dispatch_async(dispatch_get_main_queue(), ^{
// create UI Image, add to subview
});


Is there some trick to doing ui stuff inside a gcd block?



In response to mattjgalloway's comment, I'm simply trying to load a big image in a background thread. Here's the full code that I tried originally:



dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{

UIImage* img = [[UIImage alloc] initWithContentsOfFile: path];

dispatch_async(dispatch_get_main_queue(), ^{

imageView = [[[UIImageView alloc] initWithImage: img] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFill;
CGRect photoFrame = self.frame;
imageView.frame = photoFrame;
[self addSubview:imageView];

});

});


I simplified it so that I was running everything inside the main queue, but even then it didn't work. I figure if I can't get the whole thing to work in the main queue, no way the background queue stuff will work.





No comments:

Post a Comment