I am relatively new to objective-c, and having an issue of thread synchronization. I am trying to return an image to the user (through the user supplied image url). I am initiating the image download in a separate thread, with the thread function declared and defined in my current class. The problem is though the thread is getting executed, my image downloading functionality is not working (i.e none of the NSURLConnection methods are getting called.
My class function for initiating thread and image download is:
- (NSMutableData*)download:(NSString*)strURL
{
self.strURLData=strURL;
[NSThread detachNewThreadSelector:@selector(threadMethod:) toTarget:[ICacheImageDownloadMgr class] withObject:self];
//Here ICacheImageDownloadMgr is my current class
while(!bCompletionFlag)
{
if(bCompletionFlag)//bCompletionFlag is set to TRUE in NSURLConnection::connectionDidFinishLoading method after successful image download
{
return currentData;
}
}
}
My only motive here is to return “currentData” after the image download process has completed, to the user.
And the thread method declared in my current class (i.e., ICacheImageDownloadMgr) is:
+ (void) threadMethod:(ICacheImageDownloadMgr*)param
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
if(param.currentData)
{
[param.currentData release];
param.currentData=nil;
}
param.currentData = [[NSMutableData alloc]initWithLength:0];
NSURL *myURL = [[NSURL alloc] initWithString:param.strURLData];
NSURLRequest *URLRequest = [NSURLRequest requestWithURL: myURL];
param.urlcon = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self startImmediately:YES];
[myURL release];
param.dataLock = [[NSLock alloc]init];
while(!param.bCompletionFlag)
{
if([param.dataLock tryLock])
{
if(param.bCompletionFlag)//bCompletionFlag is set to TRUE in NSURLConnection::connectionDidFinishLoading method after successful image download, along with NSLock unlock call
{
break;
}
}
}
[pool release];
}
Please let me know as to what I am doing wrong here? It seems both my threads here are into blocking and that’s why my NSURLConnection methods are not getting called. Again, as stated earlier, my only aim is to return “currentData” to the user.
Thanks,
In your code:
param.urlcon = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self startImmediately:YES];will start an async connection which relies on delegate methods to let you manage the ongoing transfer. You are not providing the implementation of your delegate methods, so I cannot say what is happening there,
On another note, since you are starting a thread for your requests, you could simplify your life and make them synchronous (and actually I think this is what you were aiming at in the first place), so you do not have to deal with the delegate protocol. You can use the
method for that, e.g.: