Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCD dispatch_async and NSURLConnection

I wanted a quick and easy way to get data from a URL without having to mess with delegates.

Is there anything wrong with the following?

// Use gcd
dispatch_queue_t queue = dispatch_queue_create("com.dowork", 0);
dispatch_queue_t main = dispatch_get_main_queue();

//  do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue, ^{ 

   // Do work in the background
    NSData *response = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];

   dispatch_async(main, ^{ 

       // Update UI
       self.data = response;
       [self.tableView reloadData];


   });//end
});//end

I thought I read somewhere long ago that using the NSURLConnection synchronous method in a background thread would cause memory leaks. Is this true?

Are there any issues with the codes that is posted there? Any issues with assigning the data to self.data within the block?

like image 820
Nic Hubbard Avatar asked Oct 08 '22 14:10

Nic Hubbard


1 Answers

If you are targeting ios5 and later, there's NSURLConnection's sendAsynchronousRequest:queue:completionHandler:

To answer your specific question, it looks to me like response might leak: I don't know if there is an implicit autorelease pool on GCD threads.

Done some research now: GCD threads have their own autorelease pools but you don't know when they will be drained. You probably want to bracket the first two statements with an explicit autorelease pool.

See also Do you need to create an NSAutoreleasePool within a block in GCD?

like image 141
JeremyP Avatar answered Oct 20 '22 06:10

JeremyP