5

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?

Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

1 Answers1

4

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?

Community
  • 1
  • 1
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • I realize that, and have tested some implementations with it. But, it is still limited for what I need to do. The method I show above is so nice and easy to get the `NSData`, all other async methods seem to be a 2 step process with delegates. So, still wondering about my original question. – Nic Hubbard Feb 23 '12 at 09:56
  • Thanks, so you think it is safe to do it this way, as long as I add my own autorelease pool? – Nic Hubbard Feb 23 '12 at 10:06
  • @Nic: Probably safe even without your own autorelease pool but things may hang around longer than you want. – JeremyP Feb 23 '12 at 10:14