Memory leak while using performSelectorInBackground - ios

I am new to iOS development. I am facing problems while running a background thread. In my code resetUi is running on main UI thread, Now I am starting a background thread to fetch an image data and update my image. Everything works fine, but memory is leaking when call is made to performSelectorInBackground.
Please let me know where I am doing wrong. Also please suggest if there is a better way to update my image while fetching from an URL(dataWithContentsOfURL).
[Update]
Instrument is displaying 2 separate leaks one at perfromSelectorInBackground and other at UIImage imageWithData. I guess something is going terribly wrong with imageupdate(imageWithData)
-(void)updateData{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
profileName.text = oAuthTwitter.screen_name;
if(profilePic.image == nil){
NSString *urlString = #"https://api.twitter.com/1/users/profile_image/";
urlString = [urlString stringByAppendingFormat:oAuthTwitter.screen_name];
urlString = [urlString stringByAppendingFormat:#"?size=bigger"];
profilePic.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]];
[activityIndicator stopAnimating];
[activityIndicator release];
}
[pool drain];
}
- (void)resetUi{
if (oAuthTwitter.oauth_token_authorized) {
profilePic.hidden = NO;
profileName.hidden = NO;
NSLog(#"Resetting to authorised state");
[self performSelectorInBackground:#selector(updateData) withObject:nil];
}else{
NSLog(#"Resetting Twitter UI to non-authorized state.");
profilePic.hidden = YES;
profileName.hidden = YES;
}
}

I think you should use
[pool release];
rather than
[pool drain];
which is far more better practice.
Also can you try to release activityIndicator in the main thread?
From the code you have given I can't find any other cause for leak.. Have you tried to run your code using leak instrument and static analyzer?

Related

Multiple webservice Making UI unresponsive

The problem is that I am calling multiple webservices on my homepage and the webservice is returning me the images and text from the server. During this process the UI become fully unresponsive for say 1-2 minutes which is looking very bad as I cant do anything. I heard about dispatch and tried to implement it but I dont get any results.May be I am doing something wrong.
What I want now that I want to that I want to run this process in background So that a user can interact with the UI during the fetching operation from the server. I am implementing my code just tell me where to use dispatch.
-(void)WebserviceHomeSlider{
if([AppDelegate appDelegate].isCheckConnection){
//Internet connection not available. Please try again.
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Internate error" message:#"Internet connection not available. Please try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
return;
}else {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:ServiceUrl#"fpMainBanner" parameters:nil success:^(AFHTTPRequestOperation *operation,id responseObject)
{
//NSLog(#"JSON: %#", responseObject);
arrSlider = [responseObject objectWithJSONSafeObjects];
[_slideshow setTransitionType:KASlideShowTransitionSlide];
_slideshow.gestureRecognizers = nil;
[_slideshow addGesture:KASlideShowGestureSwipe];
// [_slideshow addImagesFromResources:[self getImages]]; // Add
// [_slideshow addTextFromResources:[self getText]];
// [slideShow subtextWithImages:[self getsubText]];
[_slideshow addImagesFromResources:[self getImages] stringArray:[self getText] stringsubArray:[self getsubText]];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
}
Just tell me where to use dispatch or edit my code using dispatch if possible. I have gone through some examples but still my concept is not clear. Which dispatch method id best (DEFAULT or BACKGROUND). I will be very thankful to You.
This is the code you are looking for . Just tell me where to edit it using dispatch
-(NSArray *)getText{
NSMutableArray *textArr = [[NSMutableArray alloc] init];
for(int i=0; i<[arrSlider count];i++)
{
texxt=[[arrSlider objectAtIndex:i ]valueForKey:#"title" ];
[textArr addObject:[texxt uppercaseString]];
}
return textArr;
}
-(NSArray *)getsubText{
NSMutableArray *subtext = [[NSMutableArray alloc] init];
for(int i=0; i<[arrSlider count];i++)
{
subbtext=[[arrSlider objectAtIndex:i ]valueForKey:#"tagline_value" ];
if(i==8)
{
subbtext=#"MAKE YOURSELF STAND OUT GET YOUR FREE CARDS!";
}
NSLog(#"subtext is,,.,.,,.,%#.%#",#"k",subbtext);
[subtext addObject:[subbtext uppercaseString]];
}
return subtext;
}
-(NSArray *)getImages
{
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for(int i=0; i<[arrSlider count];i++)
{
pathh=[[arrSlider objectAtIndex:i ]valueForKey:#"filepath" ];
NSString *newString = [pathh stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *imageURL = [NSURL URLWithString:newString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *originalImage = [UIImage imageWithData:imageData];
CGSize destinationSize = CGSizeMake(320, 158);
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// [whotshotimgview setImage:image];
[mArr addObject: img];
}
return mArr;
}
[_slideshow addImagesFromResources:[self getImages] stringArray:[self getText] stringsubArray:[self getsubText]];
The problem here is that you didn't showed implementation of addImagesFromResources method. You probably have to implement GCD in this method because i guess you are fetching images and setting on UI by this your main thread is getting blocked.
You are trying to access the UIView from thread other than the main which causes the UI unresponsiveness.
Please use this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[_slideshow setTransitionType:KASlideShowTransitionSlide];
_slideshow.gestureRecognizers = nil;
[_slideshow addGesture:KASlideShowGestureSwipe];
// [_slideshow addImagesFromResources:[self getImages]]; // Add
// [_slideshow addTextFromResources:[self getText]];
// [slideShow subtextWithImages:[self getsubText]];
[_slideshow addImagesFromResources:[self getImages] stringArray:[self getText] stringsubArray:[self getsubText]];
});
What I think is that your UI hangs due to downloading of image.
So you should use SDWebImage library that can help you to cache image and also prevent the UI getting hang. Using SDWebImage you can show the loader for the time the image is not loaded and it will cache the image. So from next time no image will be downloaded and also the UI will not hang. The link for complete reference to SDWebImage is :https://github.com/rs/SDWebImage
This block blocking your main UI to perform tasks so update this block as follow,
for(int i=0; i<[arrSlider count];i++)
{
pathh=[[arrSlider objectAtIndex:i ]valueForKey:#"filepath" ];
NSString *newString = [pathh stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
NSURL *imageURL = [NSURL URLWithString:newString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *originalImage = [UIImage imageWithData:imageData];
CGSize destinationSize = CGSizeMake(320, 158);
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// [whotshotimgview setImage:image];
[mArr addObject: img];
dispatch_async(dispatch_get_main_queue(), ^{
// If you want to refresh your UI simultaniously, you can write statement for that i.e
// yourImageView.image = img;
// Otherwise remove this queue
});
});
}
The main thread should never be used for long processing. Its there for the UI.
AFNetworking provides asynchronous functionality for downloading files. You should also be careful of thrashing the network layer with too many simulatanous downloads. I think 4 or 5 is the max the last time I tested.
So the flow of execution should be as follows.
The controller sets up the slideshow, sends the downloading of the images to a background thread(automatically handled by AFNetworking), passing a completion block to it. In this completion block you need to dispatch the work back to the main thread using GCD, dispatch_async to dispatch_get_get_main_queue
Keep your main thread's run loop available for user interaction.
It is because the images are loading in another thread and you are populating your slider right after getting the data.
It is better to implement this protocol method of KASlidershow to use the slideshow in a more memory efficient way.
(UIImage *)slideShow:(KASlideShow *)slideShow imageForPosition:(KASlideShowPosition)position
{
pathh=[[arrSlider objectAtIndex:i ]valueForKey:#"filepath" ];
NSString *newString = [pathh stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
NSURL *imageURL = [NSURL URLWithString:newString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *originalImage = [UIImage imageWithData:imageData];
CGSize destinationSize = CGSizeMake(320, 158);
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// [whotshotimgview setImage:image];
[mArr addObject: img];
return img;
});
}
i didn't try the code but i hope it will work with little changes in variable names. Good luck

Updating UI (labels) while downloading Images in iOS

This is the function to download images , in this function i have to update the UI, the UILabels that shows total images and counter value (downloaded images).
thats why i am calling a thread.
-(void) DownloadImages
{
NSLog(#"Images count to download %lu",(unsigned long)[productID count]);
if ([productID count] > 0)
{
// Document Directory
NSString *myDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (i = 0; i < [productID count]; i++)
{
[NSThread detachNewThreadSelector: #selector(UpdateLabels) toTarget:self withObject:nil];
// [self UpdateLabels]; this does not work….
NSLog(#"image no %d", i);
//[self Status];
NSString *imageURL = [NSString stringWithFormat:#"http://serverPath/%#/OnlineSale/images/products/%#img.jpg",clientSite,[productID objectAtIndex:i]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
// Reference path
NSString *imagePath = [NSString stringWithFormat:#"%#/%#-1-lrg.jpg",myDirectory,[productID objectAtIndex:i]];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[imageData writeToFile:imagePath atomically:YES];
}
NSLog(#"Downloading images completed...");
}
}
Problem:
- here for every new image i have to call every time a new NSThread, there may be thousands of images and it looks bad that there will be thousands threads.
in simulator i have tested it for 3000 images, but in my iPad when testing it gives the error,,,
App is Exited and terminated due to memory pressure.
i guess the error is due to this calling approach of new thread every time.
what i am doing wrong here.?????????????
i have searched there are two different options but i don't know which one is right option,
Options are:
- [self performSelectorInBackground:#selector(UpdateLabels) withObject:nil];
- [NSThread detachNewThreadSelector: #selector(UpdateLabels) toTarget:self withObject:nil];
and i also want to know that if i use
[NSThread cancelPreviousPerformRequestsWithTarget:self];
just after the call of selector, is it right approach or not..???
My suggestion is to use NSOperationQueue . you could then set the maxConcurrentOperationCount property to whatever you like.
In addition in your case is the best approach.
Make some research on what are your maxConcurrentOperationCount with how many concurrent thread your iphone could run without any issue.
NSOperationQueue will manage this for you run new thread with this limitation.
It should look something like this:
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
[myQueue setMaxConcurrentOperationCount:500];
for (i = 0; i < [productID count]; i++) {
[myQueue addOperationWithBlock:^{
// you image download here
}];
}
but check apple reference first.

IOS Application Loading Data From Web

I am trying to load data from web with few simple steps:
NSData *JSONData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"******"]];
NSObject *json = [JSONData objectFromJSONData];
NSArray *arrayOfStreams = [json valueForKeyPath:#"programs"];
NSDictionary *stream = [arrayOfStreams objectAtIndex:0];
NSString *str = [[NSString alloc]initWithString:[stream valueForKey:#"image"]];
NSURL *urlForImage1 = [NSURL URLWithString:str];
NSData *imageData1 = [NSData dataWithContentsOfURL:urlForImage1];
_screenForVideo1.image = [UIImage imageWithData:imageData1];
But the problem is I am doing 30 of this right after my application launches...
I want to load about 5 of them, and than load others. Because when I try to load all of them at the same time, my app is not launching all of them loaded...
Is there any way that I can load first few of them, and wait, and than load others?
As for loading them, you should probably display a spinner, start loading the image in background and then replace the spinner with the image once it’s ready.
- (void) viewDidLoad {
UIActivityIndicator *spinner = …;
[self.view addSubview:spinner];
[self performSelectorInBackground:#selector(startLoadingImage)
withObject:nil];
}
- (void) startLoadingImage {
// You need an autorelease pool since you are running
// in a different thread now.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = [UIImage imageNamed:#"foo"];
// All GUI updates have to be done from the main thread.
// We wait for the call to finish so that the pool won’t
// claim the image before imageDidFinishLoading: finishes.
[self performSelectorOnMainThread:#selector(imageDidFinishLoading:)
withObject:image waitUntilDone:YES];
[pool drain];
}
- (void) imageDidFinishLoading: (UIImage*) image {
// fade spinner out
// create UIImageView and fade in
}

Memory leak when setting a UIImage in an NSOperation

I'm having an issue where relatively large images never seem to get released from memory (1MB~5MB in size). This following block of code gets called while a user scrolls through a set of images. After about 15 images the application will crash. Sometimes "didReceiveMemoryWarning" gets called, and sometimes it doesn't--the application will just crash, stop, quit debugging, and not halt on any line of code--nothing. I assume this is what happens when the device runs out of memory? Another concern is that 'dealloc' never seems to get called for the subclassed 'DownloadImageOperation'. Any ideas?
Getting and setting the image:
//Calling this block of code multiple times will eventually cause the
// application to crash
//Memory monitor shows real memory jumping 5MB to 20MB increments in instruments.
//Allocations tool shows #living creeping up after this method is called.
//Leaks indicate something is leaking, but in the 1 to 5 kb increments. Nothing huge.
DownloadImageOperation * imageOp = [[DownloadImageOperation alloc] initWithURL:imageURL localPath:imageFilePath];
[imageOp setCompletionBlock:^(void){
//Set the image in a UIImageView in the open UIViewController.
[self.ivScrollView setImage:imageOp.image];
}];
//Add operation to ivar NSOperationQueue
[mainImageQueue addOperation:imageOp];
[imageOp release];
DownloadImageOperation Definition:
.h file
#import <Foundation/Foundation.h>
#interface DownloadImageOperation : NSOperation {
UIImage * image;
NSString * downloadURL;
NSString * downloadFilename;
}
#property (retain) UIImage * image;
#property (copy) NSString * downloadURL;
#property (copy) NSString * downloadFilename;
- (id) initWithURL:(NSString *)url localPath:(NSString *)filename;
#end
.m file
#import "DownloadImageOperation.h"
#import "GetImage.h"
#implementation DownloadImageOperation
#synthesize image;
#synthesize downloadURL;
#synthesize downloadFilename;
- (id) initWithURL:(NSString *)url localPath:(NSString *)filename {
self = [super init];
if (self!= nil) {
[self setDownloadURL:url];
[self setDownloadFilename:filename];
[self setQueuePriority:NSOperationQueuePriorityHigh];
}
return self;
}
- (void)dealloc { //This never seems to get called?
[downloadURL release], downloadURL = nil;
[downloadFilename release], downloadFilename = nil;
[image release], image = nil;
[super dealloc];
}
-(void)main{
if (self.isCancelled) {
return;
}
UIImage * imageProperty = [[GetImage imageWithContentsOfFile:downloadFilename andURL:downloadURL] retain];
[self setImage:imageProperty];
[imageProperty release];
imageProperty = nil;
}
#end
Get Image Class
.m file
+ (UIImage *)imageWithContentsOfFile:(NSString *)path andURL:(NSString*)urlString foundFile:(BOOL*)fileFound {
BOOL boolRef;
UIImage *image = nil;
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
if (image==nil) {
boolRef = YES;
image = [UIImage imageWithContentsOfFile:[[AppDelegate applicationImagesDirectory] stringByAppendingPathComponent:[path lastPathComponent]]];
}
if (image==nil) {
boolRef = YES;
image = [super imageWithContentsOfFile:path];
}
if (image==nil) {
//Download image from the Internet
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setTimeOutSeconds:120];
[request startSynchronous];
NSData *responseData = [[request responseData] retain];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSData *rdat = [[NSData alloc] initWithData:responseData];
[responseData release];
NSError *imageDirError = nil;
NSArray *existing_images = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[path stringByDeletingLastPathComponent] error:&imageDirError];
if (existing_images == nil || [existing_images count] == 0) {
// create the image directory
[[NSFileManager defaultManager] createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:NO attributes:nil error:nil];
}
BOOL write_success = NO;
write_success = [rdat writeToFile:path atomically:YES];
if (write_success==NO) {
NSLog(#"Error writing file: %#",[path lastPathComponent]);
}
image = [UIImage imageWithData:rdat];
[rdat release];
}
return image;
}
Apologies for this huge block of code. I really have no idea where the problem might be here so I tried to be as inclusive as possible. Thanks for reading.
The main issue in the operation not getting deallocated is that you have a retain cycle, caused by the reference of imageOp in the completion block. Consider your code that says:
DownloadImageOperation * imageOp = [[DownloadImageOperation alloc] initWithURL:imageURL localPath:imageFilePath];
[imageOp setCompletionBlock:^(void){
//Set the image in a UIImageView in the open UIViewController.
[self.ivScrollView setImage:imageOp.image];
}];
In ARC, you would add a __weak qualifier to the operation and use that rather than imageOp within the completionBlock, to avoid the strong reference cycle. In manual reference counting, you can avoid the retain cycle through the use the __block qualifier to achieve the same thing, namely to keep the block from retaining imageOp:
DownloadImageOperation * imageOp = [[DownloadImageOperation alloc] initWithURL:imageURL localPath:filename];
__block DownloadImageOperation *blockImageOp = imageOp;
[imageOp setCompletionBlock:^(void){
//Set the image in a UIImageView in the open UIViewController.
[self.imageView setImage:blockImageOp.image];
}];
I think if you do that, you'll see your operation getting released correctly. (See the "Use Lifetime Qualifiers to Avoid Strong Reference Cycles" section of Transitioning to ARC Release Notes. I know you're not using ARC, but this section describes both the ARC and manual reference counting solutions.)
If you don't mind, I had other observations regarding your code:
You shouldn't be updating the UI from the completionBlock without dispatching it to the main queue ... all UI updates should happen on the main queue:
DownloadImageOperation * imageOp = [[DownloadImageOperation alloc] initWithURL:imageURL localPath:filename];
__block DownloadImageOperation *blockImageOp = imageOp;
[imageOp setCompletionBlock:^(void){
//Set the image in a UIImageView in the open UIViewController.
UIImage *image = blockImageOp.image;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.imageView setImage:image];
}];
}];
You're using accessor methods in your init method. As a matter of good practice, you really shouldn't. See Don’t Use Accessor Methods in Initializer Methods and dealloc in the Advanced Memory Management Programming Guide.
While we may have fixed the problem of the operation not getting released, I would suspect that unless you've already coded your UIScrollViewDelegate calls to release images that have scrolled off the visible screen, that you'll continue to have memory issues. Having said that, you may have already tackled this issue, and if so, I apologize for even mentioning it. I only raise the issue as it would just be easy to fix this NSOperation problem, but then neglect to have the scroll view release images as they scroll off the screen.
I'm not sure your subclassed NSOperation will support concurrency as you're missing some of the key methods discussed in Defining a Custom Operation in the Concurrency Programming Guide. Perhaps you have done this already, but just omitted it for brevity. Alternatively, I think it's easier if you use one of the existing NSOperation classes (e.g. NSBlockOperation) which take care of this stuff for you. Your call, but if you pursue concurrency, you'll want to make sure you set the queue's maxConcurrentOperationCount to something reasonable, like 4.
You code has some redundant retain statements. Having said that, you have the necessary release statements, too, so you've ensured that you won't have problems, but it's just a little curious. Clearly, ARC gets you out of the weeds on that sort of stuff, but I appreciate that this is a big step. But when you get a chance, take a look at ARC as it saves you from having to worry about a lot of this.
You should probably run your code through the static analyzer ("Analyze" on the "Product" menu), as you have some dead stores and the like.

I want to give a priority each background thread and excute gradually

This code generates Low memory warning because background 5 thread is almostly loading images in same time.
I want to give a priority each thread and make lock & unlock.
I would make step by step thread. image 1 loading -> image2 loading -> image3 loading -> image4 loading.
How can I do this?
viewcontroller
-(void)viewDidLoad
{
for(int i=0; i<screenshotcount ; i++)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString * url=[detailItem.mScreenshot objectAtIndex:i];
NSDictionary *args=[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:i], #"screenNum",
[NSString stringWithString:url],#"url",
nil];
[self performSelectorInBackground:#selector(loadImageScreenshot:) withObject:args];
[pool release];
}
}
loading image
-(void) loadImageScreenshot:(NSDictionary *) args
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage * screenshotImage=[UIImage imageWithStringURL:url];
NSDictionary *args2=[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:num], #"screenNum",
screenshotImage,#"image",
nil];
[self performSelectorOnMainThread:#selector(assignImageToScreenshotImageView:) withObject:args2 waitUntilDone:YES];
[pool release];
}
image add
- (void) assignImageToScreenshotImageView:(NSDictionary *)arg
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage * image= [arg objectForKey:#"image"];
UIImageView *imageview=[UIImageView alloc]init];
.
.
imageview.image=image;
[self.mScreenshotSpace addSubview:imageview];
[imageview release];
[pool release];
}
image from url
+(UIImage *)imageWithStringURL:(NSString *)strURL
{
NSURL *url =[NSURL URLWithString:strURL];
NSData * data=[[NSData alloc]initWithContentsOfURL:url options:NSDataReadingUncached error:&error];
UIImage * image=[UIImage imageWithData:data ];
[data release];
return image;
}
maybe I misunderstood your question, but from what you said, what you really want is to "serialise" the threads, that is, ensure they are executed one after the other. If this is the case I do not see a big advantage in having five (or more) threads if they spend most of the time waiting in a sort of "thread queue" :)
My 2 cents: Instead of playing with the threads' priority, maybe you should think about re-design the code to have a queue of files/images to load and a thread that dequeue and load the images one after the other. (the classic consumer/producer scenario)
If you need to speed up things you might think to have another thread doing some pre-fetching (if that make sense in your sw design/architecture)
CiaoCiao
Sergio
Sergio is right - if you can look at GCD and serialized queues, it shouldn't be too hard to migrate to it. Take a look at the videos from Apple for good how-to steps.

Resources