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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With